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

如何将Python嵌套列表转为字典后通过json.dumps生成JSON数据

问题原因

你的转换逻辑本身没有错误,异常是因为Python 3 中map()函数返回的是迭代器对象,而非列表,json.dumps()无法直接序列化迭代器类型,因此无法得到预期的JSON结果。另外你定义的函数参数命名和外层变量重名,容易引发歧义,建议调整。

修正方案

方法1:修改原有代码,将map迭代器转为列表

只需要给map()的返回值套一层list()即可正常运行:

import json

prices = [[1,2,3,4],[3,4,1,2]]

def prices_to_dict(price_item):
    price_headers = ['apple','banana','pear','orange']
    return dict(zip(price_headers, price_item))

prices_dict_list = list(map(prices_to_dict, prices))
prices_json = json.dumps(prices_dict_list)
# 输出验证:[{"apple": 1, "banana": 2, "pear": 3, "orange": 4}, {"apple": 3, "banana": 4, "pear": 1, "orange": 2}]
print(prices_json)

方法2:用列表推导式实现,可读性更高

不需要单独定义函数,代码更简洁:

import json

prices = [[1,2,3,4],[3,4,1,2]]
price_headers = ['apple','banana','pear','orange']

prices_dict_list = [dict(zip(price_headers, item)) for item in prices]
prices_json = json.dumps(prices_dict_list)

导出为JSON文件

如果需要直接写入本地JSON文件,可以使用json.dump方法,支持格式化输出避免乱码:

with open('prices.json', 'w', encoding='utf-8') as f:
    # indent参数控制缩进,ensure_ascii设为False避免中文乱码
    json.dump(prices_dict_list, f, ensure_ascii=False, indent=2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:36:04