首页 > 解决方案 > 在python中使用相同的键合并两个字典

问题描述

我想用相同的键在python中合并两个字典

字典

dict1 = { 'a1': { 'b1': { 'c1': 'd1' }}}

dict2 = { 'a1': { 'b1': { 'c2': 'd2' }}}

dict3 = { 'a1': { 'b2': { 'c3': 'd3' }}}

dict4 = { 'a2': { 'b3': { 'c4': 'd4' }}}

我希望这个合并到

dict1 = {'a1': {'b1': {'c1': 'd1', 'c2': 'd2'}, 'b2': {'c3': 'd3'}},
         'a2': {'b3': {'c4': 'd4'}}}

我尝试过合并,update但它覆盖了所有内容

提前致谢。

编辑:

我试过的代码:

dict1.update(dict2)
dict1.update(dict3)
dict1.update(dict4)

输出:

>>> dict1
{'a1': {'b1': {'c2': 'd2'}}, 'a2': {'b3': {'c4': 'd4'}}}

标签: python-3.xdictionarymerge

解决方案


问题update只在顶层有效。

def addin( d1, d2 ):
    for k,v in d2.items():
        if k not in d1:
            d1[k] = v
        else:
            addin( d1[k], v )

merged = {}
addin( merged, dict1 )
addin( merged, dict2 )
addin( merged, dict3 )
addin( merged, dict4 )
print(merged)

推荐阅读