如何向python字典中的现有键添加新字典
我有一个预定义的dicitonary:如何向python字典中的现有键添加新字典,python,Python,我有一个预定义的dicitonary: customMappingDict = {'Validated' : '', 'notValidated' : ''} 如果可能,我想将新字典(!?)作为其值添加到现有键中,如中所示: customMappingDict = {'Validated' : 'Key: 'Value', Key1: 'Value'', 'notValidated' : 'Key: 'Value', Key1
customMappingDict = {'Validated' : '',
'notValidated' : ''}
如果可能,我想将新字典(!?)作为其值添加到现有键中,如中所示:
customMappingDict = {'Validated' : 'Key: 'Value', Key1: 'Value'',
'notValidated' : 'Key: 'Value', Key1: 'Value''}
对于生成的字典,我希望调用两个预先存在的键(已验证和未验证),并从其值(!?)循环键,如下所示:
输出应为:
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]}
与'{}相同。格式(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}
你应该修正你的引号。旁注:“在你否决我之前[…]”。否决票不属于你,也不属于用户。它们只是对问题的质量和相关性的一种衡量,目的是提高质量,过滤掉不好的质量。如果有人否决了你的问题,不要将其视为个人冒犯,而是询问原因并努力提高质量;)没有得到您在此处尝试执行的操作-customMappingDict['Validated']:dict[str1]='{}.format(provLst[1])@Nitheesh如上所述,如果这是一个有效的场景,我想为当前字典中的现有键添加一个新字典。因此,您想将一个新dict作为值添加到现有dict中
{'red': {'light_red': 100.10, 'dark_red': 100.20}, 'green': 1000}