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

如何通过Python将字典正确转换为每行对应列表元素的CSV文件?

Hey there! I see the issue with your code—let's get that CSV formatted correctly for you.

What's going wrong right now

When you use pd.DataFrame([dict01]), you're passing the entire dictionary as a single row to the DataFrame. That's why pandas is treating each list (the values for keys A and B) as a single cell value, resulting in that one-row CSV with full lists in each column.

The Fix

All you need to do is remove the square brackets wrapping dict01 when creating the DataFrame. Here's the updated code (don't forget to import pandas if you haven't already):

import pandas as pd

dict01 = { "A": ["1", "2", "3", "4"], "B": [2.0, 3.0, 2.0, 5.0] }
df01 = pd.DataFrame(dict01)  # No more [] around dict01!
df01.to_csv('csv01.csv', index=False)  # index=False removes the extra index column

What this produces

Your csv01.csv will now look exactly how you want it:

A,B
1,2.0
2,3.0
3,2.0
4,5.0

Why this works

Pandas is designed to handle dictionaries directly when creating DataFrames:

  • The dictionary keys become the column names (A and B).
  • Each key's corresponding list becomes the row values for that column.
  • Pandas automatically aligns the lists by their index positions to create individual rows (so the first element of A pairs with the first element of B, and so on).

The index=False parameter is optional but recommended here—it prevents pandas from adding an extra column of default row numbers (0, 1, 2, 3) to your CSV.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 23:33:11