4

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

JustCurious
  • 111
  • 3
  • 14
  • Hereare some good answers that might help you: https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth keep searching for `deep dict update`. You should get some helpful results. – Tekay37 Jan 03 '18 at 12:18

1 Answers1

6

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

cs95
  • 330,695
  • 80
  • 606
  • 657