结合两个字典词典(Python)

有没有一种简单的方法可以在Python中组合两个字典词典?这就是我需要的:

dict1 = {'A' : {'B' : 'C'}}
dict2 = {'A' : {'D' : 'E'}}

result = dict_union(dict1, dict2)
# => result = {'A' : {'B' : 'C', 'D' : 'E'}}

我创建了一个蛮力功能,但我正在寻找一个更紧凑的解决方案:

def dict_union(train, wagon):
    for key, val in wagon.iteritems():
        if not isinstance(val, dict):
            train[key] = val
        else:
            subdict = train.setdefault(key, {})
            dict_union(subdict, val)
最佳答案
这是一个类,RUDict(用于Recursive-Update dict),它实现了您正在寻找的行为:

class RUDict(dict):

    def __init__(self, *args, **kw):
        super(RUDict,self).__init__(*args, **kw)

    def update(self, E=None, **F):
        if E is not None:
            if 'keys' in dir(E) and callable(getattr(E, 'keys')):
                for k in E:
                    if k in self:  # existing ...must recurse into both sides
                        self.r_update(k, E)
                    else: # doesn't currently exist, just update
                        self[k] = E[k]
            else:
                for (k, v) in E:
                    self.r_update(k, {k:v})

        for k in F:
            self.r_update(k, {k:F[k]})

    def r_update(self, key, other_dict):
        if isinstance(self[key], dict) and isinstance(other_dict[key], dict):
            od = RUDict(self[key])
            nd = other_dict[key]
            od.update(nd)
            self[key] = od
        else:
            self[key] = other_dict[key]


def test():
    dict1 = {'A' : {'B' : 'C'}}
    dict2 = {'A' : {'D' : 'E'}}

    dx = RUDict(dict1)
    dx.update(dict2)
    print(dx)


if __name__ == '__main__':
    test()


>>> import RUDict
>>> RUDict.test()
{'A': {'B': 'C', 'D': 'E'}}
>>>

转载注明原文:结合两个字典词典(Python) - 代码日志