Merging Dict Of Dicts And Sum Values
I'm looking for a way to merge multiple dicts with each other, which contain nested dicts too. The number of nested dicts is not static but dynamic. At the end the Final dict shoul
Solution 1:
The issue is that you need to determine what to do with a dictionary key based on the type of the value. The basic idea is:
- Input is a pair of dictionaries, output is the sum dictionary
- Step along both input dictionaries
- If a value is a dictionary, recurse
- If a value is a number, add it to the other number
This is fairly easy to implement with a comprehension:
defadd_dicts(d1, d2):
defsum(v1, v2):
if v2 isNone:
return v1
try:
return v1 + v2
except TypeError:
return add_dicts(v1, v2)
result = d2.copy()
result.update({k: sum(v, d2.get(k)) for k, v in d1.items()})
return result
The copy ensures that any keys in d2
that are not also in d1
are simply copied over.
You can now sum as follows:
ALL = add_dicts(add_dicts(COUNTRY1, COUNTRY2), COUNTRY3)
More generally, you can use functools.reduce
to do this for an indefinite number of dictionaries:
dicts = [COUNTRY1, COUNTRY2, COUNTRY3]
ALL = reduce(add_dicts, dicts)
Solution 2:
Make two functions like below:
defcal_sum(lst):
final_dict = dict()
for l in lst:
sum(final_dict,l)
return final_dict
defsum(final_dict,iter_dict):
for k, v in iter_dict.items():
ifisinstance(v, dict):
sum(final_dict.setdefault(k, dict()), v)
elifisinstance(v, int):
final_dict[k] = final_dict.get(k, 0) + v
Calling the above code as follows produces the desired output:
>>> print(cal_sum([COUNTRY1, COUNTRY2, COUNTRY3]))
{'a': {'U': 12, 'W': 23, 'V': 34, 'Y': 33, 'X': 22, 'Z': 31}, 'c': 447, 'b': {'AA': {'AAa': 26, 'AAy': 22, 'AAx': 90, 'AAz': 45}, 'BB': {'BBa': 15, 'BBz': 33, 'BBy': 67, 'BBx': 45}}}
Post a Comment for "Merging Dict Of Dicts And Sum Values"