词典列表中的值总和 [英] Sum of values in list of dictionaries
问题描述
我想获取列表中所有字典中每个键的总和值,如果其中一个字典中不存在键,则将其值视为0.
I want to get the sum values for each key in all dictionaries of a list, and if a key is not present in one of the dictionaries, then its value is considered 0.
假设我有两个这样的字典:
Suppose I have two dictionaries as such:
d1 = {'a' : 2, 'b' : 1, 'c' : 1}
d2 = {'a' : 3, 'b' : 1.1, 'd' : 2}
mylist = [d1, d2]
,我想定义一个 sum
函数,使
and I would like to define a sum
function such that
>>> sum(mylist)
{'a' : 5, 'b' : 2.1, 'c' : 1, 'd' : 2}
如果我只有两个字典,我可以做
If I only have two dictionaries, I can do
>>> for key, value in d2.items():
... try:
... d1[key] -= value
... except KeyError: #if the key isn't in d1
... d1[key] = -value
>>> d1
{'a' : 5, 'b' : 2.1, 'c' : 1, 'd' : 2}
但这不能扩展到任意数量的词典.
But this is not extendable to an arbitrary number of dictionaries.
我也尝试过
>>> {k: sum(e[k] for e in mylist) for k in mylist[0]}
{'a' : 5, 'b' : 2.1, 'c' : 1}
但是,这并没有给我没有在第一个列表中的元素的总和(在我的示例中,我缺少'd'的总和).
But this doesn't give me the sum for elements that aren't in the first list (I'm missing the sum for 'd' in my example).
我可以使用所有可能的键创建字典并将其添加到列表的开头
I could create a dictionary with all of the possible keys and add it to the front of my list
>>> d0 = {'a' : 0, 'b' : 0, 'c' : 0, 'd' : 0}
>>> newlist = [d0, d1, d2]
>>> {k: sum(e[k] for e in newlist) for k in newlist[0]}
{'a' : 5, 'b' : 2.1, 'c' : 1, 'd' : 2}
但是创建 d0
会很乏味.
我还可以使用 collections
>>> counterlist = [Counter(d) for d in mylist]
>>> result = Counter()
>>> for c in counterlist:
... result.update(c)
>>> dict(result)
但是我对来回切换到 Counter
不太满意.
But I'm not too happy about switching back and forth to Counter
.
或者,我可以实现类似更新"的功能
Or, I could implement an 'update-like' function
>>> def add(e, f):
... for key, value in f.items():
... try:
... e[key] -= value
... except KeyError:
... e[key] = -value
>>> result = dict()
>>> for d in mylist:
... add(result, d)
>>> result
{'a' : 5, 'b' : 2.1, 'c' : 1, 'd' : 2}
但是,这让我感到自己正在重新发明轮子.
But this makes me feel like I'm reinventing the wheel.
有没有更多的Python方式来做到这一点?
Is there a more pythonic way of doing this?
推荐答案
首先从您的词典列表中获取所有键并设置新词典:
First get all keys and set up a new dictionary from your list of dictionaries:
d1 = {'a' : 2, 'b' : 1, 'c' : 1}
d2 = {'a' : 3, 'b' : 1.1, 'd' : 2}
mylist = [d1, d2]
sum_dict = dict.fromkeys(set().union(*mylist), 0)
在那之后,简单地遍历字典和键列表很简单:
After that that is simple to just iterate over the list of dictionaries and the keys:
for d in mylist:
for k in d.keys():
sum_dict[k] += d[k]
这篇关于词典列表中的值总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!