Python,合并多层次字典

4

可能重复:
python: 字典中的字典合并

该问题可能与其他问题相似,可以参考上述链接。这是一个关于Python中如何合并字典中的字典的问题。
my_dict= {'a':1, 'b':{'x':8,'y':9}}
other_dict= {'c':17,'b':{'z':10}}
my_dict.update(other_dict)

结果是:

{'a': 1, 'c': 17, 'b': {'z': 10}}

但我希望你能翻译这个:

{'a': 1, 'c': 17, 'b': {'x':8,'y':9,'z': 10}}

我该怎么做呢?(可能有简单的方法吗?)

你想要合并的字典中,dict是唯一的“特殊”类型吗? - robert
@antti:我认为对于我的问题可能有一个更简单的解决方案,因为嵌套的级别(深度)是预先知道的(在这种情况下只有2级)。 - blues
@robert:是的。只是字典。 - blues
如果my_dict包含某个键的字典,但other_dict包含非字典(或反之),您希望出现什么行为?例如,my_dict={'a':1}other_dict={'a':{'b':2}} - Edward Loper
1个回答

8
import collections # requires Python 2.7 -- see note below if you're using an earlier version
def merge_dict(d1, d2):
    """
    Modifies d1 in-place to contain values from d2.  If any value
    in d1 is a dictionary (or dict-like), *and* the corresponding
    value in d2 is also a dictionary, then merge them in-place.
    """
    for k,v2 in d2.items():
        v1 = d1.get(k) # returns None if v1 has no value for this key
        if ( isinstance(v1, collections.Mapping) and 
             isinstance(v2, collections.Mapping) ):
            merge_dict(v1, v2)
        else:
            d1[k] = v2

如果您不使用Python 2.7+,则将isinstance(v, collections.Mapping)替换为isinstance(v, dict)(用于严格类型)或hasattr(v, "items")(用于鸭子类型)。请注意,如果某些键存在冲突--即,如果d1具有字符串值并且d2对该键具有字典值--那么此实现仅保留d2的值(类似于update)。

这很容易做到。我生成的字典与字符串/整数冲突的情况不会发生。谢谢。 - blues

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接