Python深度合并字典数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20656135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:57:47  来源:igfitidea点击:

Python deep merge dictionary data

python

提问by evolution

Is there a library in Python that I can use to deep merge dictionaries:

Python 中是否有一个库可用于深度合并字典:

The following:

下列:

a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }

When i combine I want this to look like:

当我结合时,我希望它看起来像:

a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }

采纳答案by vincent

I hope I don't reinvent the wheel but the solution is fairly short. And, superfun to code.

我希望我不要重新发明轮子,但解决方案很短。而且,编码超级有趣。

def merge(source, destination):
    """
    run me with nosetests --with-doctest file.py

    >>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
    >>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }
    >>> merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }
    True
    """
    for key, value in source.items():
        if isinstance(value, dict):
            # get node or create one
            node = destination.setdefault(key, {})
            merge(value, node)
        else:
            destination[key] = value

    return destination

So the idea is to copy the source to the destination, and every time it's a dict in the source, recurse. So indeed you will have a bug if in A a given element contains a dict and in B any other type.

所以这个想法是将源复制到目标,并且每次它是源中的字典时,递归。因此,如果在 A 中给定元素包含一个 dict 而在 B 中包含任何其他类型,则确实会出现错误。

[EDIT] as said in comments the solution was already here : https://stackoverflow.com/a/7205107/34871

[编辑] 正如评论中所说,解决方案已经在这里:https: //stackoverflow.com/a/7205107/34871