对一个字典中的每个键的多个值求和? [英] Summing multiple values of each key in a dict?
本文介绍了对一个字典中的每个键的多个值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的python字典.
I have a python dictionary, which looks like this.
{ 'item1' : [1,2,3,4,5,6],
'item2' : [2,3,1],
.
.
.
'item n' : [4,2,4,3,2]
}
现在,我的要求是,我想添加此字典&的数值.显示为:-
Now my requirement is that i want to add the numeric values of this dict & to show it as :-
{ 'item1' : [21],
'item2' : [6],
.
.
.
'item n' : [15]
}
我只希望对每个键的多个值求和&显示.仅供参考,我正在使用附加函数.下面是我的代码.
I just want the multiple values of each key to be summed up & displayed. FYI, I am using an append function. Below is my code.
for row in range(2,sheet2.max_row):
for column in "D":
cell_name = "{}{}".format(column, row)
for column2 in "P":
cell_name2 = "{}{}".format(column2,row)
arrdata2dict.setdefault(sheet2[cell_name].value,[])
arrdata2dict[sheet2[cell_name].value].append(sheet2[cell_name2].value)
推荐答案
您可以动态地创建带有总和的字典:
You could create the dictionary with the sums on-the-fly:
Result = dict([(key, sum(values)) for key, values in yourDict.items()])
# or...
Result = {key: sum(values) for key, values in yourDict.items()}
在这里,新字典的值将是数字,但是如果您真的需要它们成为列表,则可以将调用sum
括在方括号中:[sum(values)]
.
Here, the values of the new dictionary will be numbers, but if you really need them to be lists, you could enclose the call to sum
in square brackets: [sum(values)]
.
这篇关于对一个字典中的每个键的多个值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文