如何合并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" } ] }]
原代码问题分析
你尝试的代码执行失败,核心问题有三点:
- 错误的变量访问方式:直接使用
item_list_one变量无效,该变量未定义,必须通过字典键取值,比如item["item_list_one"] - 循环变量重复覆盖:外层循环已使用
index变量,内层再次使用会覆盖原有值,导致逻辑混乱 - 冗余的循环写法:遍历列表无需用
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
相关产品推荐
相关产品推荐

