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

如何在Python中从列表生成指定格式的JSON文件?

实现方法

当然可以实现,核心是将两个列表的对应元素配对,再生成目标结构的字典列表,最后写入JSON文件。

步骤1:生成目标数据结构

使用Python内置的zip()函数,将两个列表的对应元素一一配对,再通过列表推导式生成你需要的字典列表:

import json

arr_of_id_by_user = [1, 2, 3]
arr_of_wallet_amount = [100, 3400, 200]

# 生成目标结构的列表
result = [
    {"user": user_id, "wallet amount": amount}
    for user_id, amount in zip(arr_of_id_by_user, arr_of_wallet_amount)
]

步骤2:写入JSON文件

用json.dump()将数据写入文件,indent参数可以让JSON格式更易读:

# 写入JSON文件
with open("wallet_data.json", "w") as f:
    json.dump(result, f, indent=4)

你之前的问题分析

  • 你写的for循环里直接return,会在第一次循环就终止,只能返回第一个元素,且没有关联钱包金额数据;
  • 单独用json.dumps()只是把数据转成JSON字符串,没有写入文件,也没处理两个列表的配对关系。

备选:用普通循环实现(适合新手理解)

如果觉得列表推导式不够直观,也可以用普通循环逐个构建字典:

result = []
for i in range(len(arr_of_id_by_user)):
    user_dict = {
        "user": arr_of_id_by_user[i],
        "wallet amount": arr_of_wallet_amount[i]
    }
    result.append(user_dict)

# 同样用json.dump()写入文件
with open("wallet_data.json", "w") as f:
    json.dump(result, f, indent=4)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:41:03