+2 votes
in Programming Languages by (73.8k points)
edited by

I want to create a CSV file to save a dictionary. The keys of the dictionary should be columns and values should be rows. How can I do it?

E.g. 

The following dictionary should be written to CSV as follows:

 dict = {'A':[1,2,3,4,5],'B':[10,20,30,40,50],'C':[100,200,300,400,500]}
 

ABC
110100
220200
330300
440400
550500

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

Pandas dataframe's to_csv() function can be used to write a dictionary to a comma-separated values (csv) file.

Here is an example to create a CSV file using Pandas dataframe:

import pandas as pd
dict = {'A':[1,2,3,4,5],'B':[10,20,30,40,50],'C':[100,200,300,400,500]}
df=pd.DataFrame(dict)  #create dataframe using dictionary
df.to_csv('test.csv',index=False)   #save dictionary in test.csv

If you also want to add an index to your CSV file, just remove "index=False" from the last line. You CSV will look like this:

ABC
0110100
1220200
2330300
3440400
4550500


...