问题
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'}}
What I got?
{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'}}
What I need
{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'}}
I followed merging "several" python dictionaries but I have two different dictionaries that I need to merge. Help please...
回答1:
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"
}
}
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).
来源:https://stackoverflow.com/questions/48077115/merge-two-dictionary-with-same-key