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

如何根据code与land字段合并字典列表同组项生成最终列表?

问题:合并列表中同code和land的字典项,累加size和value

需求规则

  • 若字典的code和land字段均相同,将该字典加入最终列表;
  • 若后续字典的code和land与已存在的项相同,则将size和value累加到对应项,其余字段保留首次出现的内容;
  • 若code和land不同,则直接作为新字典加入最终列表。

原代码问题

原代码仅实现了直接添加字典的功能,未处理同code+land组合项的合并逻辑,无法完成size和value的累加。

完善后的代码

import json

mylist = [
    {
        "size": 1,
        "code": "300",
        "content": "xyz",
        "land": "AB",
        "value": 5
    },
    {
        "size": 1,
        "code": "300",
        "name": "xyz",
        "land": "AB",
        "value": 10
    },
    {
        "size": 1,
        "code": "400",
        "content": "abc",
        "land": "KK",
        "value": 12
    }
]

final = []
# 用临时字典存储已合并的项,键为(code, land)的元组
temp_dict = {}

for item in mylist:
    key = (item["code"], item["land"])
    if key in temp_dict:
        # 累加size和value
        temp_dict[key]["size"] += item["size"]
        temp_dict[key]["value"] += item["value"]
    else:
        # 首次出现,存入副本避免修改原数据
        temp_dict[key] = item.copy()

# 将临时字典的值转为列表,得到最终结果
final = list(temp_dict.values())

with open('stackoverflowResponse.json', 'w') as resp:
    json.dump(final, resp, indent=2)

代码说明

  1. 使用(code, land)元组作为唯一标识键,确保同组合的字典被归为一类;
  2. 遍历过程中,若键已存在则直接累加size和value,不存在则存入字典副本;
  3. 最终将临时字典的所有值转换为列表,得到符合要求的结果。

运行后生成的stackoverflowResponse.json内容如下:

[
  {
    "size": 2,
    "code": "300",
    "content": "xyz",
    "land": "AB",
    "value": 15
  },
  {
    "size": 1,
    "code": "400",
    "content": "abc",
    "land": "KK",
    "value": 12
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 14:20:10