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

Python中如何按product_id聚合字典列表,实现qty求和并收集req_id

Python按product_id聚合字典列表同时收集req_id的实现

现有代码存在两个核心问题:

  • 硬按索引取字典值的方式稳定性差,若字典键顺序变动会直接导致逻辑错误,建议直接通过键名取值
  • 中间聚合字典仅存储了qty总和,没有预留存储req_id的位置,无法实现后续的字段拼接

解决思路

  • 调整中间聚合字典的结构,每个product_id对应的值同时记录累计qty和req_id集合
  • 遍历原始数据时同步完成qty累加和req_id收集
  • 最后将聚合后的中间结构转换为需要的输出格式

完整实现代码

mydict = [
    {"product_id": '1', "qty": 2,'req_id':'1'},
    {"product_id": '1', "qty": 3,'req_id':'2'},
    {"product_id": '2', "qty": 4,'req_id':'3'},
    {"product_id": '2', "qty": 5,'req_id':'5'},
    {"product_id": '2', "qty": 5,'req_id':'6'},
    {"product_id": '3', "qty": 5,'req_id':'7'},
]

# 中间聚合字典,key为product_id,value为{累计qty, reqId列表}
agg_map = {}
for item in mydict:
    pid = item['product_id']
    # 若pid不在聚合映射中,先初始化
    if pid not in agg_map:
        agg_map[pid] = {
            'qty': 0,
           'reqId': []
        }
    # 累加qty
    agg_map[pid]['qty'] += item['qty']
    # 收集req_id,修正原示例中不合法的重复key写法,每个req_id单独存为字典
    agg_map[pid]['reqId'].append({'req_id': item['req_id']})

# 转换为最终输出的列表格式
result = []
for pid, agg_data in agg_map.items():
    result.append({
        'product_id': pid,
        'qty': agg_data['qty'],
       'reqId': agg_data['reqId']
    })

print(result)

输出结果说明

运行代码得到的合法结构如下,原期望示例中同一个字典存在重复req_id键属于语法错误,实际运行时重复key会被覆盖,仅能保留最后一个值:

[
    {'product_id': '1', 'qty': 5, 'reqId': [{'req_id': '1'}, {'req_id': '2'}]},
    {'product_id': '2', 'qty': 14, 'reqId': [{'req_id': '3'}, {'req_id': '5'}, {'req_id': '6'}]},
    {'product_id': '3', 'qty': 5, 'reqId': [{'req_id': '7'}]}
]

如果确实需要reqId是只含单个字典的结构,可以将收集req_id的代码替换为:

# 仅适配原示例的非标准结构时使用
if not agg_map[pid]['reqId']:
    agg_map[pid]['reqId'].append({})
agg_map[pid]['reqId'][0][f'req_id_{item["req_id"]}'] = item['req_id']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:00:01