Nobi Nobi - 7 months ago 7
Python Question

How to merge a list of dicts, summing values for repeated keys

In this list of dictionaries, I want to sum up the

values
of matching keys so that the output is as seen below:

dict_x = [{(1, 2): 100}, {(1, 3): 150}, {(1, 3): 150, (3, 4): 150}, {(4, 5): 10, (1, 3): 10, (3, 4): 10}, {(5, 6): 15}]

output:{(1, 2): 100, (1, 3): 310, (3, 4): 160, (4, 5): 10, (5, 6): 15}


I have read through some pages like How can I count the occurrences of a list item in Python? and Count how many times a part of a key appears in a dictionary python while they count the occurrence of the matching elements, they do not quite do a multiple summation of matching elements. Thank you for your time.

Answer

Here's a way to do it in one pass with collections.Counter:

>>> from collections import Counter
>>> sum(map(Counter, dict_x), Counter())
Counter({(1, 2): 100, (1, 3): 310, (3, 4): 160, (4, 5): 10, (5, 6): 15})

Previous response:

Maybe not the most efficient way, but for a small list you can do this in two passes:

>>> keys = [k for d in dict_x for k in d]
>>> {k: sum(d.get(k, 0) for d in dict_x) for k in keys}
{(1, 2): 100, (1, 3): 310, (3, 4): 160, (4, 5): 10, (5, 6): 15}

The first line gets all the keys, and the second line sums the results. I'm almost positive there's some more clever way to do this using python builtins... I'll think on it.