merge two dictionary with same key

Question:

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…

Asked By: JustCurious

||

Answers:

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).

Answered By: cs95
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'}}

"""
Answered By: Soudipta Dutta
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.