Skip to content
Advertisement

Python Dictionary to Multiple CSV files

So I have a dictionary of 98 elements and I need to write each key:value to a CSV file.

For example:

{‘Group1′:values,’Group2’:values}, etc…

So in this example I would need two (2) csv files:

  1. Group1_output.csv
  2. Group2_output.csv

I am thinking I need a for loop but I am getting a little stuck:

for element in DataFrameDict:
    element.to_csv(f'{element}_output.csv')

Advertisement

Answer

Try this since your data is stored in a dict:

for key, values in dict.items(): 
    f = open("{}_output.csv".format(key),"w")
    f.write(key) 
    for i in values: 
       f.write("," + str(i))
    f.close()
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement