Python深度合并字典数据

evo*_*ion 19 python

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

下列:

a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }
Run Code Online (Sandbox Code Playgroud)

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

a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }
Run Code Online (Sandbox Code Playgroud)

vin*_*ent 37

我希望我不重新发明轮子,但解决方案相当短.而且,超级代码.

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
Run Code Online (Sandbox Code Playgroud)

所以我的想法是将源复制到目的地,每次它都是源中的dict,递归.因此,如果A在给定元素中包含dict而在B中包含任何其他类型,那么确实会有错误.

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

  • +1 - 在我们不关心冲突的情况下,这似乎比 DUP 更直接 (2认同)
  • 请注意,这是在原地修改了“目的地”字典! (2认同)
  • @Arel 说的话。删除 return 语句可能是有意义的,因为它有点欺骗性。 (2认同)
  • 因 case: ({'b': {'c': 1}}, {'b': 1}) 而失败,因为预期为 {'b': {'c': 1}}。修复方法是在 setdefault 之后检查原始类型,如果是,则默认为 {}。 (2认同)