Macintosh1997
Macintosh1997

Reputation: 105

How can I create a csv from a dictionary

I have a very unique situation here. My dictionary has string keys and pandas.DataFrame values:

d = {'0':df1,'1':df2,'2':df3,...,'1000':df1001}

I want to create a seperate csv file for df1, df2, df3 and so on up to df1001 with the file names as '0'.csv,'1'.csv,'2'.csv and so on upto '1000'.csv respectively.

I have tried using the pandas to_csv but that does not help the cause. Can anyone please help me out here.

Thanks in advance.

Upvotes: 1

Views: 59

Answers (2)

erip
erip

Reputation: 16985

Calling to_csv should definitely work.

for k, v in d.items():
    v.to_csv("{0}.csv".format(k))

Upvotes: 5

nielsvg
nielsvg

Reputation: 25

I would recommand using the pandas library. The pandas library can easily create a dataframe from a dict. This dataframe can be stored as a CSV file.

import pandas as pd
df = pd.DataFrame.from_dict(dict)

Now you can save the pandas dataframe as a CSV file:

df.to_csv('results.csv', index=False, header=False)

Upvotes: -1

Related Questions