我有一本字典,我需要在其中使用另一個字典中的鍵附加新值,盡管我使 for 回圈正常作業,但我被要求對其進行串列理解。有人可以幫我嗎
代碼:
for key, value in functionParameters.items():
if type(value) in [int, float, bool, str]:
if key not in self.__variables:
self.__variables[key] = value
任何幫助將不勝感激...
uj5u.com熱心網友回復:
由于您想創建/更新 a dict,您需要使用dict comprehension -
self.__variables = {**self.__variables, **{k: v for k, v in functionParameters.items() if type(v) in [int, float, bool, str] and k not in self.__variables}}
解釋 -
z = {**x, **y}將 dicts 合并x為y一個新的 dictz。{k: v for k, v in functionParameters.items() if type(v) in [int, float, bool, str] and k not in self.__variables}模仿你的for回圈并創建一個新的dict- 我們將原始
self.__variablesdict 與上面新創建的 dict 合并并將其保存為self.__variables.
這是一個簡化的作業示例 -
functionParameters = {"20": 20, "string_val": "test", "float": 12.15, "pre-existing_key": "new-val", "new_type": [12, 12]}
variables = {"old_key": "val", "pre-existing_key": "val"}
variables = {**variables, **{k: v for k, v in functionParameters.items() if type(v) in [int, float, bool, str] and k not in variables}}
print(variables)
印刷 -
{'old_key': 'val', 'pre-existing_key': 'val', '20': 20, 'string_val': 'test', 'float': 12.15}
請注意,pre-existing_key輸出中的鍵的值和缺少的new_type鍵,因為對應的值是 a list。
uj5u.com熱心網友回復:
key以這種方式檢查 a 是否在陣列中使用是不正確的:
if key not in self.__variables: # not correct
如果你這樣做,它會檢查是否 key 存在作為里面的一個值self.__variables
我不知道你這樣做的理由!,但你可以用try & except這樣的方式來處理它:
for key, value in functionParameters.items():
if type(value) in [int, float, bool, str]:
try:
if self.__variables[key] is not None:
self.__variables[key] = value
except Exception ignored:
pass
uj5u.com熱心網友回復:
你應該用dict comprehension這個。代碼應該是這樣的
self.__variables = {**self.__variables, **{key: value for key, value in functionParameters.items() if type(value) in [int, float, bool, str] and key not in self.__variables}}
uj5u.com熱心網友回復:
您可以更新:
self.__variables.update({
key: value
for key, value in functionParameters.items()
if key not in self.__variables and type(value) in [int, float, bool, str]
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441604.html
