首页 > 解决方案 > 如何在不破坏的情况下合并两个字典

问题描述

我有两本字典,我想将它们组合起来。

dict1 = {'abc': {'test1': 123}}
dict2 = {'abc': {'test2': 456}}

我想结束

{'abc': {'test1': 123, 'test2': 456}}

如果dict2 = {'abc': 100}那时我想要:

{'abc' 100}

我试过dict1.update(dict2)了,但这给了我{'abc': {'test2': 456}}

有没有一种pythonic方法可以做到这一点?

标签: python

解决方案


IIUC,您可以执行以下操作:

def recursive_update(d1, d2):
    """Updates recursively the dictionary values of d1"""

    for key, value in d2.items():
        if key in d1 and isinstance(d1[key], dict) and isinstance(value, dict):
            recursive_update(d1[key], value)
        else:
            d1[key] = value


dict1 = {'abc': {'test1': 123}}
dict2 = {'abc': {'test2': 456}}

recursive_update(dict1, dict2)

print(dict1)

输出

{'abc': {'test1': 123, 'test2': 456}}

请注意,递归仅适用于作为字典的值。例如:

dict1 = {'abc': {'test1': 123}}
dict2 = {'abc': 100}

产生(如预期):

{'abc': 100}

推荐阅读