Home > database >  Altering 10% of Values in Dictionary Comprehension using Python
Altering 10% of Values in Dictionary Comprehension using Python

Time:11-19

I am having an issue making a dictionary comprehension. I have made list comprehensions before, and thought they'd be similar, but with {} instead.

I am pretty sure my random logic is sound, for the task I want though.

Updated dict:

import random

DLM = '~'  # deliminator

programmatic_dict = {
  "brand~test": "Ford",
  "model~test": "Mustang",
  "year~test": "2019"
}
print(programmatic_dict)

programmatic_dict = {programmatic_dict[key]: val   DLM   key.rsplit(DLM, 1)[1] else val for key, val in programmatic_dict.items() if random.randint(0,9) == 9}
print(programmatic_dict)

Error:

Traceback (most recent call last):
  File "/usr/lib/python3.8/py_compile.py", line 144, in compile
    code = loader.source_to_code(source_bytes, dfile or file,
  File "<frozen importlib._bootstrap_external>", line 846, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./prog.py", line 13
    programmatic_dict = {programmatic_dict[key]: val   DLM   key.rsplit(DLM, 1)[1] else val for key, val in programmatic_dict.items() if random.randint(0,2) == 2}
                                                                                   ^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.8/py_compile.py", line 150, in compile
    raise py_exc
py_compile.PyCompileError:   File "./prog.py", line 13
    programmatic_dict = {programmatic_dict[key]: val   DLM   key.rsplit(DLM, 1)[1] else val for key, val in programmatic_dict.items() if random.randint(0,2) == 2}
                                                                                   ^
SyntaxError: invalid syntax

Desired Output:

programmatic_dict = {
  "brand~test": "Ford",
  "model~test": "Mustang~test",  # subtag in key string, added randomly at 10% (unlikely)
  "year~test": "2019"
}

Where am I going wrong on my dictionary comprehension code line?

Please let me know if there is anything else I can add to post to help further clarify (as I know it's a strange task what I'm wanting done).

CodePudding user response:

2 Amendments:

  • reference any key as key:,
  • else statement of else val, for the 90% of the time I didn't want any change to my value.
programmatic_dict = {key: val   DLM   key.rsplit(DLM, 1)[1] if random.randint(0, 9) == 9 else val for key, val in programmatic_dict.items()}

Article Ctrl F: "Python dictionary comprehension if else"

  • Related