Suppose I have the following list:
[{'name': 'Amy', 'count': 1}, {'name': 'Amy', 'count': 2}, {'name': 'Peter', 'count': 1}]
How could I group it and sum the count in order to get the following out:
[{'name': 'Amy', 'count': 3}, {'name': 'Peter', 'count': 1}]
Thanks.
解决方案
You can use a collecions.Counter:
from collections import Counter
l = [
{'name': 'Amy', 'count': 1},
{'name': 'Amy', 'count': 2},
{'name': 'Peter', 'count': 1}
]
c = Counter()
for v in l:
c[v['name']] += v['count']
Result:
>>> c
Counter({'Amy': 3, 'Peter': 1})
>>> [{'name': name, 'count': count} for name, count in c.items()]
[{'count': 3, 'name': 'Amy'}, {'count': 1, 'name': 'Peter'}]