我们说我的字典定义为:
dict_1['x']['y'] = 'something'
另一个字典定义为:
dict_2['x'] = {}
dict_2['x']['z'] = 'something else'
我怎样才能这样做
由于dict_1.update(dict_2)
, dict_2['x']['z'] = 'something else'
只会添加delete dict_1['x']['y']
但不会dict_2['x'] = {}.
答案 0 :(得分:1)
dict_1['x'].update(dict_2['x'])
答案 1 :(得分:1)
这以递归方式解决了这个问题。
def mergeDicts(dict1, dict2):
for key in dict2:
if key in dict1:
dict1[key] = mergeDicts(dict1[key], dict2[key])
else:
dict1[key] = dict2[key]
return dict1