如何对分配给字典列表中的键的值求和? [英] How to sum the values assigned to a key in a list of dictionaries?
问题描述
我的字典清单如下:
A=[
{key1 : val11, key2 : val21, key3 : val31, key5 : val51, key6 : val61},
{key2 : val22, key3 : val32, key5 : val52, key6 : val62},
{key1 : val13, key2 : val23, key4 : val43, key5 : val53},
{key1 : val14, key3 : val34, key4 : val44, key5 : val54, key6 : val64},
{key4 : val45, key5 : val55, key6 : val65}
]
如您所见,字典的长度并不相同,每个字典中的key : value
也不一定相似.我想知道如何对所有字典中为每个键分配的值求和:
As you see the length of the dictionaries are not the same and also the key : value
in each dictionary are not necessarily similar. I was wondering how to sum the values assigned for each key in all dictionaries:
例如对于key4: (val43 + val44 + val45)
或key3: (val31 + val32 + val34)
.
推荐答案
从此开始-
A = [{1 : 5, 2 : 3, 3 : 4}, {1 : 1, 5: 10, 3: 2}, {100 : 2}]
- 使用
map
将每个字典转换为 - 将每个
Counter
对象与sum
相加
Counter
- Convert each dict to a
Counter
usingmap
- Sum each
Counter
object withsum
from collections import Counter
r = sum(map(Counter, A), Counter())
r
Counter({1: 6, 2: 3, 3: 6, 5: 10, 100: 2})
关于Counter
的伟大之处在于,您可以将它们很好地相加. sum
的第二个参数是"sum"的开头.如果要返回字典(而不是Counter
),请调用dict(r)
.
The great thing about Counter
s is that you can add them up, quite nicely. The second argument to sum
is the start of the "sum". If you want a dictionary back (instead of a Counter
), call dict(r)
.
请注意,当您的字典只有具有数字值的键时,此解决方案才有效.
Note that this solution works when your dicts only have keys with numeric values.
这篇关于如何对分配给字典列表中的键的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!