Python,合并多级词典

时间:2012-05-22 14:13:27

标签: python dictionary

  

可能重复:
  python: Dictionaries of dictionaries merge

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}}

我该怎么做? (可能以一种简单的方式?)

1 个答案:

答案 0 :(得分: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