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
)的值
'dict'是字典中您想要组合的唯一“特殊”类型吗? – robert
@antti:我认为对于我的问题,可能会有一个更简单的解决方案,因为预先知道嵌套层次(深度)(在这种情况下仅为2) – blues
@robert:是的。只是字迹 – blues