Home > Net >  Combining two dictionaries with sub-dictionaries and updating values?
Combining two dictionaries with sub-dictionaries and updating values?

Time:11-15

I have two dictionaries:

d1 = {'Cat': {'White': 1}, 'Dog': {'Brown': 4, 'White': 2}}

d2 = {'Cat': {'Grey': 6, 'White': 3}, 'Rabbit': {'Brown': 4, 'White': 2}}

And I want to combine these dictionaries into a single dictionary while updating values for common values in the sub-dictionaries of d1 and d2 for matching keys in d1 and d2.

So if I combine d1 and d2, I would like to get:

combined = {'Cat': {'Grey': 6, 'White': 4}, 'Dog': {'Brown': 4, 'White': 2}, 'Rabbit': {'Brown': 4, 'White': 2}}

I am new to python so any help is appreciated.

CodePudding user response:

I guess there is also a module for that purpose (e.g. collections module -> counter) but this is one solution:

def combine_dicts(d1, d2):
    combined = {}
    for key in d1:
        combined[key] = {}
        for key2 in d1[key]:
            combined[key][key2] = d1[key][key2]
    for key in d2:
        if key in combined:
            for key2 in d2[key]:
                if key2 in combined[key]:
                    combined[key][key2]  = d2[key][key2]
                else:
                    combined[key][key2] = d2[key][key2]
        else:
            combined[key] = {}
            for key2 in d2[key]:
                combined[key][key2] = d2[key][key2]
    return combined

d1 = {'Cat': {'White': 1}, 'Dog': {'Brown': 4, 'White': 2}}
d2 = {'Cat': {'Grey': 6, 'White': 3}, 'Rabbit': {'Brown': 4, 'White': 2}}

print(combine_dicts(d1, d2))

Output: {'Cat': {'White': 4, 'Grey': 6}, 'Dog': {'Brown': 4, 'White': 2}, 'Rabbit': {'Brown': 4, 'White': 2}}
  • Related