![](/img/trans.png)
[英]Python: How to iterate over a list of dictionaries and add each dictionary as value to a new dictionary with a unique key - no repeats
[英]How to add new dictionaries to an existing Key in a dictionary python
我有這個預定義的字典:
customMappingDict = {'Validated' : '',
'notValidated' : ''}
如果可能,我想將新字典(?,)添加到現有鍵作為其值:如:
customMappingDict = {'Validated' : 'Key: 'Value', Key1: 'Value'',
'notValidated' : 'Key: 'Value', Key1: 'Value''}
對於生成的字典,我想調用兩個預先存在的鍵(Validated 和 notValidated)並從其值(?:) 中循環鍵,如下所示:
for key in customMappingDict['Validated'].keys():
pass
...
Output 應該是:
key, key1
我試過的:
if condition:
str1 = '{}'.format(provLst[0])
customMappingDict['Validated']: dict[str1]= '{}'.format(provLst[1])
else:
str2 = '{}'.format(provLst[0])
customMappingDict['notValidated']: dict[str2] = '{}'.format(provLst[1])
我在 PyCharm 中得到的磨損:
Class 'type' does not define '__getitem__', so the '[]' operator cannot be used on its instances
使用collections.defaultdict
將為您省去很多麻煩。 defaultdict
的想法是創建一個具有默認值的字典。 在這種情況下,默認值也將是字典。
你可以這樣做:
from collections import defaultdict
customMappingDict = defaultdict(dict)
if condition:
str1 = '{}'.format(provLst[0])
customMappingDict['Validated'][str1] = f'{provLst[1]}'
else:
str2 = '{}'.format(provLst[0])
customMappingDict['notValidated'][str2] = f'{provLst[1]}'
旁注: f{provLst[0]}
與'{}'.format(provLst[0])
相同,只是更簡潔!
嘗試這個
假設我有一個字典
d = {'red': 100, 'green': 1000}
現在我想將 'red' 的值更改為 dict
d['red'] = dict()
d['red']['light_red'] = 100.10
d['red']['dark_red'] = 100.20
現在將
{'red': {'light_red': 100.10, 'dark_red': 100.20}, 'green': 1000}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.