可能重复:
python:字典的字典合并
my_dict= {'a':1, 'b':{'x':8,'y':9}}
other_dict= {'c':17,'b':{'z':10}}
my_dict.update(other_dict)
Run Code Online (Sandbox Code Playgroud)
结果是:
{'a': 1, 'c': 17, 'b': {'z': 10}}
Run Code Online (Sandbox Code Playgroud)
但我想要这个:
{'a': 1, 'c': 17, 'b': {'x':8,'y':9,'z': 10}}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?(可能以一种简单的方式?)
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
Run Code Online (Sandbox Code Playgroud)
如果你没有使用Python 2.7+,那么替换isinstance(v, collections.Mapping)为isinstance(v, dict)(用于严格打字)或hasattr(v, "items")(用于鸭子打字).
请注意,如果某个键存在冲突 - 即,如果d1具有字符串值且d2具有该键的dict值 - 则此实现仅保留d2中的值(类似于update)