user9185533
user9185533

Reputation: 17

How to sum the values assigned to a key in a list of dictionaries?

I have list of dictionaries like below:

A=[
    {key1 : val11, key2 : val21, key3 : val31, key5 : val51, key6 : val61},
    {key2 : val22, key3 : val32, key5 : val52, key6 : val62},
    {key1 : val13, key2 : val23, key4 : val43, key5 : val53},
    {key1 : val14, key3 : val34, key4 : val44, key5 : val54, key6 : val64},
    {key4 : val45, key5 : val55, key6 : val65}
]

As you see the length of the dictionaries are not the same and also the key : value in each dictionary are not necessarily similar. I was wondering how to sum the values assigned for each key in all dictionaries:

For instance for key4: (val43 + val44 + val45) or for key3: (val31 + val32 + val34).

Upvotes: 0

Views: 104

Answers (2)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

You may also use collections.defaultdict to get the count of all the values corresponding to each key. All you need to do is to iterate each element and sum the values to the defaultdict. For example:

my_list = [
     {'key1': 2, 'key2': 7},
     {'key2': 6, 'key3': 8},
     {'key1': 7, 'key4':9} 
 ]

from collections import defaultdict
my_counter = defaultdict(int)

for my_dict in my_list:                 # iterate your `list`
    for key, value in my_dict.items():  # iterate "key", "value" pairs of your `dict`
        my_counter[key] += value        # sum the "value" and add to the dict

This will return you the dict as:

>>> my_counter
defaultdict(<type 'int'>, {'key3': 8, 'key2': 13, 'key1': 9, 'key4': 9})

Upvotes: 2

cs95
cs95

Reputation: 402493

Starting with this -

A = [{1 : 5, 2  : 3, 3 : 4}, {1 : 1, 5: 10, 3: 2}, {100 : 2}]

Here's one way of getting what you want, using the collections.Counter data structure -

  1. Convert each dict to a Counter using map
  2. Sum each Counter object with sum

from collections import Counter
r = sum(map(Counter, A), Counter())

r
Counter({1: 6, 2: 3, 3: 6, 5: 10, 100: 2})

The great thing about Counters is that you can add them up, quite nicely. The second argument to sum is the start of the "sum". If you want a dictionary back (instead of a Counter), call dict(r).

Note that this solution works when your dicts only have keys with numeric values.

Upvotes: 3

Related Questions