Python 深度合并字典数据

标签 python

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

最佳答案

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

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] 正如评论中所说,解决方案已经在这里:https://stackoverflow.com/a/7205107/34871

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

相关文章:

python - 如何连接到 boto 中的现有 CloudSearch 域?

python - 使用正则表达式从列表中删除数量

python - 并行化 IO 密集型 for 循环 : stupid idea?

python - 'numpy.float6 4' object has no attribute ' 情节'

python - binance python 库 0.7.3 给出回溯错误 'endTime' ;合法范围

python - 在 python 中从 sys.argv 传递目录名

python - 与 curselection 相关的元组索引超出范围错误(tkinter)

python - 在保持文件夹结构的同时读取图像

Python 2.7 Tkinter : How would I config the shape under the mouse with key press

python - Scipy.linalg.eig() 给出与 GNU Octave 的 eig() 不同的特征向量