You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优雅地将多个Python字典按type字段分组聚合count为列表

方案1:使用collections.defaultdict(推荐,可读性最高)

只需要一次遍历即可完成,无需提前初始化key:

from collections import defaultdict

a = {'type': 'Low', 'count': 184} 
b = {'type': 'Low', 'count': 186} 
c = {'type': 'Low', 'count': 97} 
d = {'type': 'Medium', 'count': 1000} 
e = {'type': 'High', 'count': 2000} 

item_list = [a, b, c, d, e]
result = defaultdict(list)

for item in item_list:
    result[item['type']].append(item['count'])

# 如果需要转为普通字典,可加:result = dict(result)
print(result)

输出和要求的结构完全一致。

方案2:使用字典setdefault方法(无需导入模块)

如果不想额外导入依赖,可以用原生字典的setdefault方法,同样仅需一次遍历:

a = {'type': 'Low', 'count': 184} 
b = {'type': 'Low', 'count': 186} 
c = {'type': 'Low', 'count': 97} 
d = {'type': 'Medium', 'count': 1000} 
e = {'type': 'High', 'count': 2000} 

item_list = [a, b, c, d, e]
result = {}

for item in item_list:
    result.setdefault(item['type'], []).append(item['count'])

print(result)

setdefault会自动判断key是否存在,不存在则初始化对应值为传入的空列表,存在则直接返回已有的列表,可直接追加元素。

方案3:使用itertools.groupby(适合复杂分组场景)

如果需要更复杂的分组逻辑,可以用itertools.groupby,注意使用前需要先对列表按分组字段排序,否则不连续的同类型项会被分为多个组:

from itertools import groupby

a = {'type': 'Low', 'count': 184} 
b = {'type': 'Low', 'count': 186} 
c = {'type': 'Low', 'count': 97} 
d = {'type': 'Medium', 'count': 1000} 
e = {'type': 'High', 'count': 2000} 

item_list = [a, b, c, d, e]
# 先按type字段排序
sorted_list = sorted(item_list, key=lambda x: x['type'])
result = {
    typ: [i['count'] for i in group]
    for typ, group in groupby(sorted_list, key=lambda x: x['type'])
}

print(result)

内容的提问来源于stack exchange,提问作者scoopseven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:15:03