简体   繁体   中英

Python dictionary sum values

I'm using Python 2.7 and I have a large dictionary that looks a little like this

{J: [92704, 238476902378, 32490872394, 234798327, 2390470], M: [32974097, 237407, 3248707, 32847987, 34879], Z: [8237, 328947, 239487, 234, 182673]}

How can I sum these by value to create a new dictionary that sums the first values in each dictionary, then the second, etc. Like

{FirstValues: J[0]+M[0]+Z[0]}

etc

In [4]: {'FirstValues': sum(e[0] for e in d.itervalues())}
Out[4]: {'FirstValues': 33075038}

where d is your dictionary.

print [sum(row) for row in zip(*yourdict.values())]

yourdict.values() gets all the lists, zip(* ) groups the first, second, etc items together and sum sums each group.

from itertools import izip_longest
totals = (sum(vals) for vals in izip_longest(*mydict.itervalues(), fillvalue=0))
print tuple(totals)

In English...

  1. zip the lists (dict values) together, padding with 0 (if you want, you don't have to).
  2. Sum each zipped group

For example,

mydict = {
    'J': [1, 2, 3, 4, 5], 
    'M': [1, 2, 3, 4, 5], 
    'Z': [1, 2, 3, 4]
}
## When zipped becomes...
([1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 0])
## When summed becomes...
(3, 6, 9, 12, 10)

It does really not make sense to create a new dictionary as the new keys are (probably) meaningless. The results don't relate to the original keys. More appropriate is a tuple as results[0] holds the sum of all values at position 0 in the original dict values etc.

If you must have a dict, take the totals iterator and turn it into a dict thus:

new_dict = dict(('Values%d' % idx, val) for idx, val in enumerate(totals))

I don't know why do you need dictionary as output, but here it is:

dict(enumerate( [sum(x) for x in zip(*d.values())] ))

Say you have some dict like:

d = {'J': [92704, 238476902378, 32490872394, 234798327, 2390470], 
     'M': [32974097, 237407, 3248707, 32847987, 34879], 
     'Z': [8237, 328947, 239487, 234, 182673]}

Make a defaultdict (int)

from collections import defaultdict
sum_by_index = defaultdict(int)
for alist in d.values():
    for index,num in enumerate(alist): 
        sum_by_index[index] += num

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM