Python:字典值的总和列表

时间:2017-07-10 05:47:48

标签: python list

我有以下结构:

"Labour": [{
    "load": 5.00
}, {
    "edge": 0.00
}, {
    "unload": 5.00
}, {
    "load": 5.00
}, {
    "edge": 0.00
}, {
    "unload": 5.00
}, {
    "load": 5.00
}, {
    "edge": 0.00
}, {
    "unload": 5.00
}, {
    "load": 0.00
}, {
    "edge": 0.00
}, {
    "unload": 0.00
}, {
    "load": 0.00
}, {
    "edge": 0.00
}, {
    "unload": 0.00
}],

如何添加值,以便将所有载荷,边缘,卸载等加在一起。此外,字典有更多的键,我还需要通过键搜索和添加它们。我使用的是Python 2.7。

4 个答案:

答案 0 :(得分:3)

您可以使用Counter累积每个词典中所有键的所有值:

from collections import Counter

lst = [{
    "load": 5.00
},
...,
{
    "edge": 0.00
}]

dct = Counter()

for d in lst:
   for k, v in d.items():
      dct[k] += v 

print(dct)
# Counter({'load': 15.0, 'unload': 15.0, 'edge': 0.0})
print(sum(dct.values()))
# 30

如果您不需要管理负数,这样可以正常工作,否则,您需要使用说collections.defaultdict,将默认工厂设置为float

答案 1 :(得分:0)

你可以这样做:

total = 0
for item in dic['Labour']:
    for val in item.values():
        total += val

编辑:

如果您只想将相同的类型加在一起,则可以改为:

total = {}

for item in dic['Labour']:
    for key,val in item.items():
        if key in total:
            total[key] +=val
        else:
            total[key] = val

答案 2 :(得分:0)

sum([i.values()[0] for i in list_of_dicts])

如果您只需要选择与特定键组相对应的值,您可以执行以下操作:

keys=['load', 'edge' ] 
sum([i[k] for k in keys for i in list_of_dicts if k in i])

答案 3 :(得分:0)

简单直截了当:

如果您的词典是(我添加了两个新值):

d = {"Labour": [{"load": 5.00}, 
           {"edge": 0.00}, 
           {"unload": 5.00}, 
           {"load": 5.00}, 
           {"edge": 0.00}, 
           {"unload": 5.00}, 
           {"load": 5.00}, 
           {"edge": 0.00}, 
           {"unload": 5.00}, 
           {"load": 0.00}, 
           {"edge": 0.00}, 
           {"unload": 0.00}, 
           {"load": 0.00}, 
           {"edge": 0.00}, 
           {"unload": 0.00}, 
           {"new_val": 5.00}, 
           {"new_val_2": 5.00}],}

然后你可以定义这个小函数:

def sum_dicts_by_key(k, biglist):
    sum = 0
    for sdict in biglist['Labour']:
        sum += sdict.get(k,0)
    return sum

然后像:

一样使用它
sum_by_key = dict()
for small_dict in d['Labour']:
    k = small_dict.keys()[0]
    sum_by_key[k] = sum_dicts_by_key(k, d)

print('key list %s' % sum_by_key.keys())
print('Sum by key %s' % sum_by_key)
print('Total sum %s' % sum(sum_by_key.values()))

结果是:

key list ['load', 'new_val', 'edge', 'new_val_2', 'unload']
Sum by key {'load': 15.0, 'new_val': 5.0, 'edge': 0.0, 'new_val_2': 
            5.0, 'unload': 15.0}
Total sum 40.0