如何合并字典的字典? [英] How to merge dictionaries of dictionaries?

查看:103
本文介绍了如何合并字典的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要合并多个词典,例如,这就是我的内容:

I need to merge multiple dictionaries, here's what I have for instance:

dict1 = {1:{"a":{A}}, 2:{"b":{B}}}

dict2 = {2:{"c":{C}}, 3:{"d":{D}}

A B CD是树的叶子,如{"info1":"value", "info2":"value2"}

With A B C and D being leaves of the tree, like {"info1":"value", "info2":"value2"}

词典的级别(深度)未知,可能是{2:{"c":{"z":{"y":{C}}}}}

There is an unknown level(depth) of dictionaries, it could be {2:{"c":{"z":{"y":{C}}}}}

在我的情况下,它代表目录/文件结构,其中节点为docs,而节点为文件.

In my case it represents a directory/files structure with nodes being docs and leaves being files.

我想将它们合并以获得:

I want to merge them to obtain:

 dict3 = {1:{"a":{A}}, 2:{"b":{B},"c":{C}}, 3:{"d":{D}}}

我不确定如何使用Python轻松做到这一点.

I'm not sure how I could do that easily with Python.

推荐答案

这实际上很棘手-特别是如果您希望在事物不一致时获得有用的错误消息,同时正确地接受重复但一致的条目(此处没有其他答案的话) ....)

this is actually quite tricky - particularly if you want a useful error message when things are inconsistent, while correctly accepting duplicate but consistent entries (something no other answer here does....)

假设您没有大量的条目,那么递归函数是最简单的:

assuming you don't have huge numbers of entries a recursive function is easiest:

def merge(a, b, path=None):
    "merges b into a"
    if path is None: path = []
    for key in b:
        if key in a:
            if isinstance(a[key], dict) and isinstance(b[key], dict):
                merge(a[key], b[key], path + [str(key)])
            elif a[key] == b[key]:
                pass # same leaf value
            else:
                raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
        else:
            a[key] = b[key]
    return a

# works
print(merge({1:{"a":"A"},2:{"b":"B"}}, {2:{"c":"C"},3:{"d":"D"}}))
# has conflict
merge({1:{"a":"A"},2:{"b":"B"}}, {1:{"a":"A"},2:{"b":"C"}})

请注意,这会使a发生突变-将b的内容添加到a(也将返回).如果您想保留a,可以将其命名为merge(dict(a), b).

note that this mutates a - the contents of b are added to a (which is also returned). if you want to keep a you could call it like merge(dict(a), b).

agf指出(如下),您可能有两个以上的词典,在这种情况下,您可以使用:

agf pointed out (below) that you may have more than two dicts, in which case you can use:

reduce(merge, [dict1, dict2, dict3...])

将所有内容添加到dict1.

where everything will be added to dict1.

[注意-我编辑了我的初始答案以使第一个参数发生变化;使减少"更易于解释]

[note - i edited my initial answer to mutate the first argument; that makes the "reduce" easier to explain]

ps,您还需要from functools import reduce

这篇关于如何合并字典的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆