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

Python处理API返回字典列表 按站点SKU汇总生成嵌套字典

按工位分组聚合SKU数量的实现方案

需求说明

调用API拉取数据后,需将返回结果处理为嵌套字典格式,规则如下:

  • 原始返回数据为列表结构,每条记录包含SKU完整描述、目标工位、数量三个字段,示例:
[
    {
        "skuNO": "SK0011 - Green Stator with Terminal Box",
        "toStationLocation": "Line 1 - Station 1",
        "quantity": "1"
    },
    {
        "skuNO": "SK0011 - Green Stator with Terminal Box",
        "toStationLocation": "Line 1 - Station 2",
        "quantity": "1"
    },
    {
        "skuNO": "SK0011 - Green Stator with Terminal Box",
        "toStationLocation": "Line 1 - Station 2",
        "quantity": "3"
    }
]
  • 输出要求:按工位位置分组,从SKU描述字段中提取纯SKU编号,汇总同工位同SKU的总数量,示例输出:
{
    "Line 1 - Station 2": {"SK0011": 4},
    "Line 1 - Station 1": {"SK0011": 1}
}
  • 原有实现使用zip、基础字典方法未达到预期,缺陷代码如下:
final_dict = {}
for x in data:
        int_sku = []
        int_qty = []
        int_sku.append(x['skuNO'])
        int_qty.append(x['quantity'])
        zipped = dict(zip(int_sku, int_qty))
        if x['toStationLocation'] not in final_dict:
            final_dict[x['toStationLocation']] = zipped
        else:
            for key,val in final_dict.items():
                for k,v in val.items():
                    print(k,v)
                    if k == int_sku[0]:
                       v = int(int_qty[0]) + int(v)

备注:只要能实现「工位+SKU」双维度的数量聚合,其他合理数据结构的实现均可采纳。

可直接运行的实现代码

无依赖原生实现

不需要引入任何第三方库/标准库额外模块,逻辑清晰易修改:

final_dict = {}
for record in data:
    # 提取纯SKU编号:按短横线分割后取第一段,去除首尾空格
    sku_code = record["skuNO"].split("-")[0].strip()
    station = record["toStationLocation"]
    count = int(record["quantity"])

    # 工位键不存在时先初始化空字典
    if station not in final_dict:
        final_dict[station] = {}
    # 同工位下SKU键不存在时初始化数量为0
    if sku_code not in final_dict[station]:
        final_dict[station][sku_code] = 0
    # 累加数量
    final_dict[station][sku_code] += count

运行后输出结果和预期完全匹配。

简化写法(使用标准库defaultdict)

如果想减少键存在性判断的样板代码,可以用collections模块的defaultdict:

from collections import defaultdict

final_dict = defaultdict(lambda: defaultdict(int))
for record in data:
    sku_code = record["skuNO"].split("-")[0].strip()
    station = record["toStationLocation"]
    count = int(record["quantity"])
    final_dict[station][sku_code] += count

# 如需转成普通原生dict,追加下行代码即可
final_dict = {station: dict(sku_map) for station, sku_map in final_dict.items()}

原有代码缺陷说明

之前的代码无法得到正确结果,核心问题有4个:

  • 每次循环都重新初始化int_sku、int_qty为空列表,无法保留之前循环的累加结果
  • 没有对skuNO字段做截取处理,直接把带描述的长文本当成了SKU键,和预期的键名不一致
  • 累加数量时仅修改了循环生成的临时变量v,没有把计算后的值回写到原字典中,修改不生效
  • 处理已存在工位的逻辑时,遍历了整个final_dict的所有工位,没有直接定位当前记录对应的工位,做了大量无效遍历

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 02:27:30