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

Python中如何对列表内的字典按ids字段分组?

按ids字段分组字典列表的解决方法

问题分析

你的代码存在几个明显问题,导致输出不符合预期:

  • 遍历对象错误:定义的列表是dictionary_title,但代码中遍历的是未定义的nodes
  • 嵌套循环完全冗余:无需遍历genres列表,每个字典本身就包含ids值,可直接用它作为分组键
  • 字典键名大小写不匹配:原字典中颜色的键是'Color'(首字母大写),代码里写成了'color',会导致无法正确获取值
  • 逻辑错误:嵌套循环容易引发匹配错误,最终导致所有颜色被错误归类到同一个ids下

修正后的基础实现代码

dictionary_title = [
    {'Color': 'Green', 'ids': 878},
    {'Color': 'Pink', 'ids': 16},
    {'Color': 'Orange', 'ids': 28},
    {'Color': 'Yellow', 'ids': 9648},
    {'Color': 'Red', 'ids': 878},
    {'Color': 'Brown', 'ids': 12},
    {'Color': 'Black', 'ids': 28},
    {'Color': 'White', 'ids': 14},
    {'Color': 'Blue', 'ids': 28},
    {'Color': 'Light Blue', 'ids': 10751},
    {'Color': 'Magenta', 'ids': 28},
    {'Color': 'Gray', 'ids': 28}
]

result = {}
for item in dictionary_title:
    ids = item['ids']
    color = item['Color']
    # 若当前ids未作为键存在,初始化空列表
    if ids not in result:
        result[ids] = []
    result[ids].append(color)

print(result)

更简洁的实现(使用collections.defaultdict)

Python标准库的defaultdict可以自动处理键不存在的情况,无需手动判断,代码更简洁:

from collections import defaultdict

dictionary_title = [
    {'Color': 'Green', 'ids': 878},
    {'Color': 'Pink', 'ids': 16},
    {'Color': 'Orange', 'ids': 28},
    {'Color': 'Yellow', 'ids': 9648},
    {'Color': 'Red', 'ids': 878},
    {'Color': 'Brown', 'ids': 12},
    {'Color': 'Black', 'ids': 28},
    {'Color': 'White', 'ids': 14},
    {'Color': 'Blue', 'ids': 28},
    {'Color': 'Light Blue', 'ids': 10751},
    {'Color': 'Magenta', 'ids': 28},
    {'Color': 'Gray', 'ids': 28}
]

result = defaultdict(list)
for item in dictionary_title:
    result[item['ids']].append(item['Color'])

# 如需转换为普通字典,使用dict(result)
print(dict(result))

输出结果

两种方法都会得到你期望的分组结果:

{878: ['Green', 'Red'], 16: ['Pink'], 28: ['Orange', 'Black', 'Blue', 'Magenta', 'Gray'], 9648: ['Yellow'], 12: ['Brown'], 14: ['White'], 10751: ['Light Blue']}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:21:03