在python中组合两个dict
我有一本python字典,如下所示在python中组合两个dict,python,dictionary,Python,Dictionary,我有一本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'] = 'va
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={}
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'}}}
如果x和y是dict,那么
z={**x,**y}
是一个dict,将x和y合并在一起要深度合并dict,您需要使用:
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的代码这里有一种实现深度合并的方法:
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
。显然你不会得到想要的输出key2
更新了key2
的check
@Gahan我可以像测试中的key1和key2一样检查吗如果是的话,如果我给出这个表达式,它会工作吗测试['key1'['key2']['key5']='val3'用户的可能副本希望保留不同的键值,即在合并x={'a':1,'b':{'y':4}}y={'b':{'x':1},'c':4}
时,输出将是{'a':1,'b':{'x':1},'c':4}
但用户希望{'a':1,'b':{'x':1,'y','4},'c''4}>output@Thaian我期望的op是{'key1':{'key2':{'key3':{'val1','key4':'val2','key5':'val3','key6':'val4'}}}}@wazza现在检查用户希望保留不同的键值,即在合并x={'a':1',b':{'y':4}y={'b':{'x','1','c':4}
时,正如您所建议的,输出将是{'a':1','b':{'x':1','c4'>'c','code'
作为输出