Python 2.7-字典中重复项的总和 [英] Python 2.7 - Sum value on duplicates in dictionary

查看:44
本文介绍了Python 2.7-字典中重复项的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的词典列表:

I have a list of dictionaries like:

list1=[{'a':'apples', 'b':'snack','count':2},{'a':'apples','b':'lunch','count':3},{'a':'apples','b':'snack','count':3}]

我需要在"a"和"b"上的列表中将重复项分组,并对其计数"求和,以便:

I need to group duplicates in the list on 'a' and 'b' and sum their 'count' such that:

list2=[{'a':'apples','b':'snack','count':5},{'a':'apples','b':'lunch','count':3}]

在此处搜索存储库,尚未发现解决方案.非常感谢您提出任何建议.

Searched through the repository here and haven't recognized a solution. Thanks very much for any pointers.

推荐答案

您可以使用带有两个元组的 defaultdict 来累加计数,然后将其推回列表...

You can use a defaultdict with a 2tuple to accumulate the counts, then push it back to a list...

list1=[{'a':'apples', 'b':'snack','count':2},{'a':'apples','b':'lunch','count':3},{'a':'apples','b':'snack','count':3}]

from collections import defaultdict
dd = defaultdict(int)
for d in list1:
    dd[d['a'], d['b']] += d['count']

list2 = [{'a': k[0], 'b': k[1], 'count': v} for k, v in dd.iteritems()]

[{'a': 'apples', 'count': 3, 'b': 'lunch'}, {'a': 'apples', 'count': 5, 'b': 'snack'}]

这篇关于Python 2.7-字典中重复项的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆