[英]Python dictionary sum values
I'm using Python 2.7 and I have a large dictionary that looks a little like this我正在使用 Python 2.7,我有一个看起来有点像这样的大字典
{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 ETC
In [4]: {'FirstValues': sum(e[0] for e in d.itervalues())}
Out[4]: {'FirstValues': 33075038}
where d
is your dictionary.其中d
是您的字典。
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. yourdict.values()
获取所有列表, zip(* )
将第一个、第二个等项目组合在一起,并对每个组sum
。
from itertools import izip_longest
totals = (sum(vals) for vals in izip_longest(*mydict.itervalues(), fillvalue=0))
print tuple(totals)
In English...用英语讲...
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.更合适的是元组,因为results[0]
在原始字典值等中保存 position 0 处的所有值的总和等。
If you must have a dict, take the totals
iterator and turn it into a dict thus:如果您必须有一个字典,请使用totals
迭代器并将其转换为字典:
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:我不知道你为什么需要字典为 output,但这里是:
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)制作一个默认字典(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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.