python字典列表中的值总和

时间:2018-06-20 08:46:18

标签: python algorithm list dictionary

这是我的字典列表:

[{'week': '23', 'total_entry': 1}, {'week': '23', 'total_entry': 4}, {'week': '24', 'total_entry': 2}] 

我想对同一周添加的total_entry值求和,所以我想要的是:

[{'week': '23', 'total_entry': 5}, {'week': '24', 'total_entry': 2}] 

我想通过写一些代码可以获得接近的结果,但是我想必须有一种非常简单的方法来得到这个结果。有人可以看看吗?

3 个答案:

答案 0 :(得分:2)

使用collections.defaultdict

from collections import defaultdict

L = [{'week': '23', 'total_entry': 1}, {'week': '23', 'total_entry': 4},
     {'week': '24', 'total_entry': 2}]

d = defaultdict(int)

for item in L:
    d[item['week']] += item['total_entry']

print(d)

defaultdict(int, {'23': 5, '24': 2})

然后使用字典理解来获取所需的格式:

res = [{'week': k, 'total_entry': v} for k, v in d.items()]

print(res)

[{'week': '23', 'total_entry': 5}, {'week': '24', 'total_entry': 2}]

答案 1 :(得分:1)

您可以使用python groupbyitertools来根据键对列表中的元素进行分组。

import itertools

input_list = [{'week': '23', 'total_entry': 1}, {'week': '23', 'total_entry': 4}, {'week': '24', 'total_entry': 2}]

new_list = []
for key, group in itertools.groupby(input_list, lambda item: item["week"]):
    new_dict = {}
    new_dict['week'] = key
    new_dict['total_entry'] = sum([item["total_entry"] for item in group])
    new_list.append(new_dict)

print(new_list)

输出:-

[{'week': '23', 'total_entry': 5}, {'week': '24', 'total_entry': 2}]

答案 2 :(得分:0)

http://localhost:8000/movies/movies
相关问题