【问题标题】:Python deep merge dictionary data [duplicate]Python深度合并字典数据[重复]
【发布时间】:2013-12-18 10:52:33
【问题描述】:

是否有 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' } } }

【问题讨论】:

标签: python


【解决方案1】:

我希望我不要重新发明轮子,但解决方案相当短。而且,编写代码非常有趣。

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

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

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

【讨论】:

  • 这很棒而且很有趣。应该早点仔细研究一下 DUP。很好地使用递归。从简短的测试来看,它似乎适合目的。我正在使用的数据始终是 a 或 b 中的 dict 类型。
  • +1 - 在我们不关心冲突的情况下,这似乎比 DUP 更直接
  • 请注意,这是在修改destination dict
  • @Arel 说了什么。删除 return 语句可能是有意义的,因为它有点欺骗性。
  • 因大小写失败:({'b': {'c': 1}}, {'b': 1}),如 {'b': {'c': 1}}是期待。修复是在 setdefault 之后检查原始类型,如果是,则默认为 {}。
猜你喜欢
  • 1970-01-01
  • 2017-02-21
  • 2018-10-16
  • 2022-01-15
  • 2021-11-05
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
相关资源
最近更新 更多