0

I'm trying to sum a number of dictionaries with identical keys to create a sum. I found the solution for 2 dictionaries here:

How to merge two Python dictionaries in a single expression?

How can I expand this to account for N number of dictionaries to chain?

    dictionary = {1:{'a':4,'b':10},0:{'a':2,'b':55}, ... N:{'a':10,'b':11}}
    for k, v in itertools.chain(dictionary[0].items(), dictionary[1].items() ...):
        c[k] += v   
Community
  • 1
  • 1
user1961
  • 1,270
  • 2
  • 17
  • 27
  • Is the desired output here `a=16` and `b=76` ? It's not clear if the key of the outer dictionary you have has any meaning – Jon Clements Oct 27 '13 at 01:20

1 Answers1

3

A better way:

from collections import Counter
totals = Counter()
for dct in dictionary.values():
    totals.update(dct)
Jon Clements
  • 138,671
  • 33
  • 247
  • 280