[英]merge two dictionary with same key
I have below 2 dictionaries that I want to merge.我有以下 2 个要合并的词典。 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.我使用
dict1.update(dict2)
但它替换了第 2 到第 1 个字典中的值。
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.我遵循合并“几个”python 词典,但我有两个不同的词典需要合并。 Help please...
请帮助...
Loop over the keys in dict1
, and retrieve the corresponding value from dict2
, and update - 循环遍历
dict1
的键,并从dict2
检索相应的值,并更新 -
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
. 在这里,我使用
dict.get
因为它允许您指定在k
不存在作为dict2
的键的情况下返回的默认值。 In this case, the default value is the empty dictionary {}
, and calling dict.update({})
does nothing (and causes no problems). 在这种情况下,默认值是空字典
{}
,并且调用dict.update({})
不执行任何操作(并且不会导致任何问题)。
def m3(a,b):
if not isinstance(a,dict) and not isinstance(b,dict):return b
for k in b:
if k in a :
a[k] = m3(a[k], b[k])
else: a[k] = b[k]
return a
d1 = {1:{"a":"A"}, 2:{"b":"B"}}
d2 = {2:{"c":"C"}, 3:{"d":"D"}}
d3 = {1:{"a":{1}}, 2:{"b":{2}}}
d4 = {2:{"c":{222}}, 3:{"d":{3}}}
d5 = {'employee':{'dev1': 'Roy'}}
d6 = {'employee':{'dev2': 'Biswas'}}
print(m3(d1,d2))
print(m3(d3,d4))
print(m3(d5,d6))
"""
Output :
{1: {'a': 'A'}, 2: {'b': 'B', 'c': 'C'}, 3: {'d': 'D'}}
{1: {'a': {1}}, 2: {'b': {2}, 'c': {222}}, 3: {'d': {3}}}
{'employee': {'dev1': 'Roy', 'dev2': 'Biswas'}}
"""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.