Python 如何合并两个满足条件的词典
例如: 我有两本字典:Python 如何合并两个满足条件的词典,python,loops,dictionary,Python,Loops,Dictionary,例如: 我有两本字典: dict1 = {'machine1': {'operative_system': 'Windows', 'Description':'This is an example'} 'machine2': {'operative_system': 'Ubuntu', 'Description':'This is another example'}} dict2 = {'machine1': {'Disk1': {'Name_disk':'example'}, 'Disk2'
dict1 = {'machine1': {'operative_system': 'Windows', 'Description':'This is an example'} 'machine2': {'operative_system': 'Ubuntu', 'Description':'This is another example'}}
dict2 = {'machine1': {'Disk1': {'Name_disk':'example'}, 'Disk2': {'Name_disk':'disk2'}}}
如何将这些“磁盘”插入第一个字典
机器的名称是相同的…您可以使用
dict.update
从dict1
更新现有子词典,并在try/except
中包装以处理keyrerror
不在dict2
for key, value in dict1.items():
try:
value.update(dict2[key])
except KeyError:
continue
后来
>>> dict1
{'machine1': {'operative_system': 'Windows',
'Description': 'This is an example',
'Disk1': {'Name_disk': 'example'},
'Disk2': {'Name_disk': 'disk2'}},
'machine2': {'operative_system': 'Ubuntu',
'Description': 'This is another example'}}
类似地,以下方法也适用
for key, value in dict1.items():
if key in dict2:
value.update(dict2[key])
到目前为止,您尝试了什么?您是否尝试了
dict.update
?您好,我尝试了使用update方法,但似乎出于此目的,它不会改变字典的结构