2012-05-22 257 views
4

可能重复:
python: Dictionaries of dictionaries mergePython的,合并多层次的字典

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

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

+0

'dict'是字典中您想要组合的唯一“特殊”类型吗? – robert

+0

@antti:我认为对于我的问题,可能会有一个更简单的解决方案,因为预先知道嵌套层次(深度)(在这种情况下仅为2) – blues

+0

@robert:是的。只是字迹 – blues

回答

5
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)的值

+2

也许可以考虑在py2.7 + –

+0

@上使用isinstance(val,collections.Mapping) AnttiHaapala很好的建议。 –

+0

这会做。与字符串/整数相冲突的情况不会发生在我从中产生字典的数据上。谢谢 – blues