This question already has answers here:
How to merge dictionaries of dictionaries?

(30个答案)


7年前关闭。




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

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

当我结合时,我希望它看起来像:
a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }

最佳答案

我希望我不会重新发明轮子,但是解决方案相当短。而且, super 有趣的代码。

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

因此,其想法是将源复制到目标,并且每次源中的命令都进行递归。因此,如果在A中给定元素包含字典而在B中包含任何其他类型,则确实存在错误。

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

关于python - Python深度合并字典数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20656135/

10-11 15:14
查看更多