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

如何合并Python中接口返回JSON内的字典列表?

问题:合并JSON结构中的两个列表字段

原始接口返回结构

接口返回的JSON解析后结构如下(注:原始JSON存在语法小错误,已忽略):

dataList = [{
    "item one" : 1234,
    "item two" : "5678",
    "item three" : "90",
    "item_list_one" : [
        {
            "first_item_list_item_one" : 1,
            "first_item_list_item_two" : "def",
            "first_item_list_item_three" : "abc"
        },
        {
            "first_item_list_item_one" : 1,
            "first_item_list_item_two" : "def",
            "first_item_list_item_three" : "abc"
        }
    ],
    "item_list_two" : [
        {
            "second_item_list_item_four" : 2,
            "second_item_list_item_five" : "mno",
            "second_item_list_item_six" : "pqr"
        },
        {
            "item_list_item_seven" : 1,
            "item_list_item_eight" : "def",
            "item_list_item_nine" : "abc"
        }
    ]
}]

需求

将每个父字典中的item_list_one和item_list_two合并为一个新的列表combined_list,保留其他原有字段,最终结构如下:

dataList = [{
    "item one" : 1234,
    "item two" : "5678",
    "item three" : "90",
    "combined_list" : [
        {
            "first_item_list_item_one" : 1,
            "first_item_list_item_two" : "def",
            "first_item_list_item_three" : "abc"
        },
        {
            "first_item_list_item_one" : 1,
            "first_item_list_item_two" : "def",
            "first_item_list_item_three" : "abc"
        },
        {
            "second_item_list_item_four" : 2,
            "second_item_list_item_five" : "mno",
            "second_item_list_item_six" : "pqr"
        },
        {
            "item_list_item_seven" : 1,
            "item_list_item_eight" : "def",
            "item_list_item_nine" : "abc"
        }
    ]
}]

原代码问题分析

你尝试的代码执行失败,核心问题有三点:

  1. 错误的变量访问方式:直接使用item_list_one变量无效,该变量未定义,必须通过字典键取值,比如item["item_list_one"]
  2. 循环变量重复覆盖:外层循环已使用index变量,内层再次使用会覆盖原有值,导致逻辑混乱
  3. 冗余的循环写法:遍历列表无需用range(len(...)),直接遍历列表元素更简洁

正确实现代码

# 遍历dataList中的每个字典元素
for item in dataList:
    # 获取两个列表,用get方法避免键不存在时报错
    list_one = item.get("item_list_one", [])
    list_two = item.get("item_list_two", [])
    
    # 合并两个列表,添加为新字段combined_list
    item["combined_list"] = list_one + list_two
    
    # 可选:如果不需要保留原列表字段,可删除它们
    if "item_list_one" in item:
        del item["item_list_one"]
    if "item_list_two" in item:
        del item["item_list_two"]

代码说明

  • item.get(key, [])确保即使字段不存在也返回空列表,避免抛出KeyError
  • 列表直接用+运算符合并,元素按原顺序拼接成新列表
  • 可选删除原字段,保持最终结构整洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:33:20