如何对 python 中的字典列表进行分组和添加计数属性?

How to group and add a count attribute to a list of dictionaries in python?

给定字典列表:

list = [{"foo": "a", "bar": "1", "baz": "A_CODE"}, 
        {"foo": "a", "bar": "12", "baz": "A_CODE"}, 
        {"foo": "b", "bar": "2", "baz": "ANOTHER_CODE"}]

根据baz对字典进行分组,得到以下最优雅的方法是什么? bar可以省略。

items = [{"foo": "a", "baz": "A_CODE", "count": 2},  
        {"foo": "b", "baz": "ANOTHER_CODE", "count": 1}]

这是我现在的做法:

items = []
for key, group in itertools.groupby(list, lambda item: item["baz"]):
    item["count"] = sum([1 for item in group])
    items.append(item)

你提供的信息不多,希望能帮到你。

from collections import defaultdict

d = defaultdict(int)
for i in list:
    d[i["baz"]]+=1
>>[{"baz":i, "count":j} for i,j in d.items()]
 [{'baz': 'A_CODE', 'count': 2}, {'baz': 'ANOTHER_CODE', 'count': 1}]