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

如何在Python中合并JSON对象并对重复键的obj_count求和?

Python合并JSON对象并按text和id求和obj_count

需求是合并两个JSON数组,当数组中对象的text和id同时相同时,将它们的obj_count字段值求和,其余对象直接保留。

示例输入

第一个JSON数组:

[
    {"text": " pen and ink and watercolour", "id": "x32505 ", "obj_count": 1855},
    {"text": " watercolour", "id": "x33202 ", "obj_count": 674},
    {"text": "pencil", "id": "AAT16013 ", "obj_count": 297}
]

第二个JSON数组:

[
    {"text": " pen and ink and watercolour", "id": "x32505 ", "obj_count": 807},
    {"text": " watercolour", "id": "x33202 ", "obj_count": 97},
    {"text": " ink", "id": "AAT15012 ", "obj_count": 297}
]

期望输出

[
   {"text":" pen and ink and watercolour","id":"x32505 ","obj_count": 2662},
   {"text":" watercolour","id":"x33202 ","obj_count": 771},
   {"text":" ink","id":"AAT15012 ","obj_count":297},
   {"text":"pencil","id":"AAT16013 ","obj_count":297}
]

解决方案

可以用字典作为临时存储,以(text, id)元组作为唯一标识键,遍历两个数组的所有对象实现obj_count累加,最后将字典值转换为列表即可得到结果。

完整代码示例:

# 定义输入的两个JSON数组
list1 = [
    {"text": " pen and ink and watercolour", "id": "x32505 ", "obj_count": 1855},
    {"text": " watercolour", "id": "x33202 ", "obj_count": 674},
    {"text": "pencil", "id": "AAT16013 ", "obj_count": 297}
]

list2 = [
    {"text": " pen and ink and watercolour", "id": "x32505 ", "obj_count": 807},
    {"text": " watercolour", "id": "x33202 ", "obj_count": 97},
    {"text": " ink", "id": "AAT15012 ", "obj_count": 297}
]

# 临时字典存储合并结果
merged_dict = {}

# 处理第一个数组
for item in list1:
    key = (item["text"], item["id"])
    if key in merged_dict:
        merged_dict[key]["obj_count"] += item["obj_count"]
    else:
        merged_dict[key] = item.copy()  # 复制对象避免修改原数据

# 处理第二个数组
for item in list2:
    key = (item["text"], item["id"])
    if key in merged_dict:
        merged_dict[key]["obj_count"] += item["obj_count"]
    else:
        merged_dict[key] = item.copy()

# 转换为最终列表格式
result = list(merged_dict.values())

# 格式化输出结果
import json
print(json.dumps(result, indent=2))

代码说明

  • 用(text, id)元组作为字典键,确保只有两个字段完全匹配时才会合并
  • 遍历数组时,若键已存在则累加obj_count,不存在则复制当前对象到字典
  • 最后将字典的值转为列表,得到符合要求的合并结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:45:12