Skip to content Skip to sidebar Skip to footer

Merge Two Dictionaries With Nested Dictionaries Into New One, Summing Same Keys And Keeping Unaltered Ones In Python

I have two dictionaries, both with a nested dictionary, and I want to merge them in a bigger dictionary. Some of the keys are different in the two dictionaries, some of them are th

Solution 1:

Seems like a use-case for a defaultdict of a defaultdict of int ...

The basic idea is that when you come across a key that isn't in the top-level defaultdict, you add the key (with an associated defaultdict(int) to store the date -> integer map as the value). When you come across a date which isn't in the nested dict, the defaultdict(int) will add the date with a default value of 0 (since int() called with no arguments returns 0).

Here's some code to make it concrete:

from collections import defaultdict
output = defaultdict(lambda: defaultdict(int))
for d in (dict1, dict2):
    forkey, values_dict in d.items():
        fordate, integerin values_dict.items():
            output[key][date] += integer

If you really want to be thorough, after the fact you can set the default_factory to None to prevent any more "default" behavior from the defaultdict:

output.default_factory = Nonefordefault_date_dictin output.values():
    default_date_dict.default_factory = None

Post a Comment for "Merge Two Dictionaries With Nested Dictionaries Into New One, Summing Same Keys And Keeping Unaltered Ones In Python"