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   
4

1 回答 1

3

更好的方法:

from collections import Counter
totals = Counter()
for dct in dictionary.values():
    totals.update(dct)
于 2013-10-27T01:16:43.417 回答