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

如何将Python嵌套字典中指定键的数据保存为CSV文件?

解决嵌套字典转指定格式CSV的问题

你可以用Python内置的csv模块快速实现需求,无需额外安装第三方库,具体步骤如下:

核心思路

你的嵌套字典中,有效数据集中在out["lower_level"]子字典内:

  • 子字典的键对应CSV的query列
  • 子字典值里的name对应category列
  • 子字典值里的confidence对应同名列,可通过四舍五入保留指定小数位

完整代码实现

import csv

# 示例嵌套字典(可替换为你的实际数据)
out = {
    "lower_level": {
        "television": {"name": "8k smart television", "confidence": 0.9041114449501038, "by": 1},
        "phone": {"name": "5g smartphone", "confidence": 0.87654321, "by": 1}
    }
}

# 定义CSV表头
csv_headers = ["query", "category", "confidence"]

# 写入CSV文件(newline=''避免生成空行)
with open("result.csv", "w", newline="", encoding="utf-8") as csv_file:
    # 用制表符分隔实现列对齐,和你示例格式匹配;如需标准逗号分隔,将delimiter改为","
    writer = csv.writer(csv_file, delimiter="\t")
    writer.writerow(csv_headers)
    
    # 遍历提取数据并写入
    for query_key, detail_dict in out["lower_level"].items():
        category_val = detail_dict["name"]
        # 保留4位小数,和示例输出一致
        confidence_val = round(detail_dict["confidence"], 4)
        writer.writerow([query_key, category_val, confidence_val])

代码说明

  1. 文件操作:用with语句自动管理文件资源,避免手动关闭文件的繁琐
  2. 分隔符选择:使用\t(制表符)作为分隔符,能让CSV内容和你示例中的对齐格式一致;如果需要标准逗号分隔的CSV,只需把delimiter="\t"改成delimiter=","
  3. 数据处理:通过round()函数对置信度做四舍五入,保证输出格式符合要求

最终输出效果

生成的result.csv内容(制表符分隔):

query      category          confidence
television 8k smart television  0.9041
phone      5g smartphone       0.8765

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:35:14