需求:存在以下两个第一层key相同的两层嵌套字典,求合并后的字典。
dic1 = {"小明": {"name": "owen", "age": 180}}
dic2 = {"小明": {"birthday": "1999-11-22", "height": 180}}
解答代码如下:
from copy import deepcopy
def merge_two_dict(dic1, dic2):
"""合并两个key相同的两层嵌套字典"""
dic = deepcopy(dic1)
for key in dic2.keys():
if key in dic:
dic[key].update(dic2[key])
print(dic)
if __name__ == '__main__':
dic1 = {"小明": {"name": "owen", "age": 180}}
dic2 = {"小明": {"birthday": "1999-11-22", "height": 180}}
merge_two_dict(dic1, dic2)
运行结果: