def _merge_dict(old_dict, new_dict):
for key, val in new_dict.items():
if old_dict.get(key) is not None and isinstance(val, dict) is True and _max_depth(val) > 0:
_merge_dict(old_dict.get(key), val)
else:
old_dict[key] = val
return old_dict
def _max_depth(root):
if isinstance(root, dict) is True and len(root) == 0:
return 0
if isinstance(root, dict) is False:
return 0
return 1 + max(_max_depth(child) for child in root.values())
a_dict = {
1: {
2: {
4: 5,
6: 7
},
3: {
8: 9
}
},
10: {
11: 12
}
}
b_dict = {
1: {
2: {
8: 7
}
}
}
if __name__ == '__main__':
print(_merge_dict(a_dict, b_dict))
a_dict.update(b_dict)
print(a_dict)
# 输出值分别为:
# {1: {2: {4: 5, 6: 7, 8: 7}, 3: {8: 9}}, 10: {11: 12}}
# {1: {2: {8: 7}, 3: {8: 9}}, 10: {11: 12}}
类似于update功能但不同于update,不同在于更新每个字典至最底层(根据自己需求设置需要更新的层数,0表示最底层,值越大层数越高,值超过自己的字典层数时等同于update)的字典值,而update更新到发现不同的某一层的字典值。