如何通过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 (
AandB). - 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
Apairs with the first element ofB, 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

