4

可能重复:
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}}

我怎样才能做到这一点?(可能以简单的方式?)

4

1 回答 1

6
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 有一个该键的 dict 值——那么这个实现只保留 d2 的值(类似于update

于 2012-05-22T14:22:26.740 回答