我有一个python字典如下
test={}
test['key1']={}
test['key1'] ['key2'] = {}
test['key1']['key2']['key3'] = 'val1'
test['key1']['key2']['key4'] = 'val2'
我有另一本词典如下
check = {}
check['key1']={}
check['key1'] ['key2'] = {}
check['key1']['key2']['key5'] = 'val3'
check['key1']['key2']['key6'] = 'val4'
我想结合这个词典,所以我做了以下
test.update(check)
但如果我在尝试打印测试字典时执行此操作,则会打印
{'key1': {'key2': {'key5': 'val3', 'key6': 'val4'}}}
但预期输出
{'key1': {'key2': {'key3': 'val1', 'key4': 'val2','key5': 'val3', 'key6': 'val4'}}}
答案 0 :(得分:0)
这是实现深度合并的一种方法:
test={}
test['key1']={}
test['key1'] ['key2'] = {}
test['key1']['key2']['key3'] = 'val1'
test['key1']['key2']['key4'] = 'val2'
check = {}
check['key1']={}
check['key1'] ['key2'] = {}
check['key1']['key2']['key5'] = 'val3'
check['key1']['key2']['key6'] = 'val4'
def deep_merge(a, b):
for key, value in b.items():
if isinstance(value, dict):
# get node or create one
node = a.setdefault(key, {})
deep_merge(value, node)
else:
a[key] = value
return a
deep_merge(test,check)
print(test)
# {'key1': {'key2': {'key3': 'val1', 'key6': 'val4', 'key5': 'val3', 'key4': 'val2'}}}
它会改变test
并使check
保持不变。
答案 1 :(得分:-1)
如果x和y是dicts,那么z = {**x, **y}
是合并x和y的字典
答案 2 :(得分:-2)
要深度合并,需要使用:
def merge(source, destination):
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
merge(value, node)
else:
destination[key] = value
return destination
test = {'key1': {'key2': {'key3': 'val1', 'key4': 'val2'}}}
check = {'key1': {'key2': {'key6': 'val4', 'key5': 'val3'}}}
print(merge(test, check))
# {'key1': {'key2': {'key3': 'val1', 'key6': 'val4', 'key4': 'val2', 'key5': 'val3'}}}
来自vincent的Python deep merge dictionary data的代码