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

Python如何根据字典键中的索引对字典列表进行分组

实现方法

核心逻辑是提取每个字典键中的索引值作为分组依据,代码实现如下:

data = [
    {'records-0': '1'}, {'records-0-item1': '2'}, {'records-0-item2': '3'},{'records-0-item3': '4'},
    {'records-1': '1'}, {'records-1-item1': '2'}, {'records-1-item2': '3'},
]

# 临时存储分组结果
group_map = {}
for item in data:
    # 提取当前字典的唯一键
    current_key = next(iter(item))
    # 从键中提取分组索引
    group_idx = int(current_key.split('-')[1])
    # 写入分组
    group_map.setdefault(group_idx, []).append(item)

# 转换为要求的输出格式,按索引排序
sortedData = [{idx: items} for idx, items in sorted(group_map.items())]

运行后得到的sortedData和你期望的输出格式完全一致,该方案支持任意大小的索引值,无需提前预设索引范围,适配用户动态生成的输入数据。


内容的提问来源于stack exchange,提问作者Yorbjörn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:45:00