用相同的键合并两个字典 [英] merge two dictionary with same key
问题描述
我要合并以下2个词典.我想合并相同的键,并且我想保留两个字典的值.我使用了 dict1.update(dict2)
,但是它替换了第2到第1字典中的值.
I have below 2 dictionaries that I want to merge. I want to merge on the same keys and I want to keep the values of both the dictionary.
I used dict1.update(dict2)
but that replaced the values from 2nd to 1st dictionary.
u'dict1', {160: {u'na': u'na'}, 162: {u'test_': u'qq', u'wds': u'wew'}, 163: {u'test_env': u'test_env_value', u'env': u'e'}, 159: {u'no' : u'test_no'}
u'dict2', {160: {u'naa': u'na'}, 162: {u'envi_specs': u'qq', u'wds': u'wew'}, 163: {u'test_env': u'test_env_value', u'ens': u's'}}
我得到了什么?
{160: {u'naa': u'na'}, 162: {u'envi_specs': u'qq', u'wds': u'wew'}, 163: {u'test_env': u'test_env_value', u'ens': u's'}}
我需要
{160: {u'naa': u'na', u'na': u'na'}, 162: {u'envi_specs': u'qq', u'wds': u'wew', u'test_': u'qq'}, 163: {u'test_env': u'test_env_value', u'ens': u's', u'env': u'e'}}
我关注了合并"several"python字典,但是我需要合并两个不同的字典.请帮助...
I followed merging "several" python dictionaries but I have two different dictionaries that I need to merge. Help please...
推荐答案
查看 dict1
中的键,并从 dict2
中检索相应的值,然后更新-
Loop over the keys in dict1
, and retrieve the corresponding value from dict2
, and update -
for k in dict1:
dict1[k].update(dict2.get(k, {})) # dict1.get(k).update(dict2.get(k, {}))
print(dict1)
{
"160": {
"naa": "na",
"na": "na"
},
"162": {
"wds": "wew",
"test_": "qq",
"envi_specs": "qq"
},
"163": {
"test_env": "test_env_value",
"ens": "s",
"env": "e"
},
"159": {
"no": "test_no"
}
}
在这里,我使用 dict.get
,因为它允许您指定在 k
不存在作为键的情况下要返回的默认值.> dict2
.在这种情况下,默认值为空字典 {}
,并且调用 dict.update({})
不会执行任何操作(并且不会造成任何问题).
Here, I use dict.get
because it allows you to specify a default value to be returned in the event that k
does not exist as a key in dict2
. In this case, the default value is the empty dictionary {}
, and calling dict.update({})
does nothing (and causes no problems).
这篇关于用相同的键合并两个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!