Reputation: 651
I'm trying to write a dictionary to csv file in python.
I'm using following solution:
Export a simple Dictionary into Excel file in python
However when i write to file in a following manner:
for key, value in dict1.iteritems():
writer.writerow([key, value])
The key and the value from dictionary are stored in single column for each item in dictionary. I would like key to be stored in first column and value to be stored in second column and to assign headers to the columns if possible. Can anyone help?
Upvotes: 1
Views: 2425
Reputation: 5921
You can do as follows using 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
Upvotes: 1