如何从Python字典创建自定义CSV文件?

2024-09-28 22:25:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建如下CSV文件:

Features, Value
f1, 1
f2, 2
f3, 3

但我明白了:

f1, f2, f3
1, 2, 3

我写的代码是:

my_dict = {'f1': 1, 'f2': 2, 'f3': 3}
with open('testcsv.csv', 'w') as f:
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

我该怎么办


Tags: 文件csv代码valuemyaswithopen
2条回答

熊猫在这里有点过分,csv模块就足够了。只是你用错了方法:

with open('testcsv.csv', 'w', newline='') as f:
    w = csv.writer(f)
    w.writerow(['Features', 'Value'])    # first write a header line
    for f, v in my_dict.items():
        w.writerow((f,v))                # then one row per item in the dict

您需要首先根据预期的结构转换数据

data = [{'Features':i,'Value':my_dict[i]} for i in my_dict]

一旦您这样做,您可以使用pandas将其保存为CSV,如下所示:

import pandas as pd
df = pd.DataFrame(data)
df.to_csv('testcsv.csv',index=None)

生成的csv:

Features,Value
f1,1
f2,2
f3,3

相关问题 更多 >