使用 Python 改变字典理解中 10% 的值

Altering 10% of Values in Dictionary Comprehension using Python

我在理解字典时遇到问题。我以前做过列表理解,并认为它们是相似的,但是用 {} 代替。

我很确定我的 random 逻辑是正确的,但对于我想要的任务。

更新的字典:

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)

错误:

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

期望的输出:

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

我的字典理解代码行哪里出错了?

请让我知道是否有任何其他我可以添加到 post 以帮助进一步澄清的内容(因为我知道这是我想要完成的一项奇怪的任务)。

2条修正案:

  • 将任意键引用为 key:
  • else else val 的语句,90% 的时间里我不希望我的值有任何改变。
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"