我试图在python中写一个字典给csv文件。
我使用以下解决方案:
Export a simple Dictionary into Excel file in python
但是,当我以下列方式写入文件时:
for key, value in dict1.iteritems():
writer.writerow([key, value])
字典中的键和值存储在字典中每个项目的单列中。我希望将密钥存储在第一列中,并将值存储在第二列中,并在可能的情况下将标头分配给列。有人可以帮忙吗?
答案 0 :(得分:1)
您可以使用 pandas :
执行以下操作import pandas as pd
dic = #your dictionnary
# Creating your dataframe from your dictionnary
df = pd.DataFrame([(k, v) for k, v in dic.iteritems()], columns=['key', 'value'])
# Store the data into a csv file
df.to_csv('your_path', sep=',') # indicate the path where to store the csv file