Search code examples
pythondataframecsvexport-to-csv

list of dictionaries to csv. Each list in a row


I'm new to dataframe here.

i have a list of dictionaries that i got from a python script:

result = [{'Name':'J','age':'5','address':'California'},
 {'Name':'Q', 'age':'10','address':'newYork'}
]

I want this output to be in a csv file where the column name is "info" and each dictionary is in a row.

Any idea how to get a csv like this :

    info
    {'Name':'J','age':'5','address':'California'}
    {'Name':'Q', 'age':'10','address':'newYork'}

Solution

  • This is an edited example from the docs assuming that all dictionaries have the exact same keys:

    import csv
    
    with open('names.csv', 'w', newline='') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=result[0].keys())
    
        writer.writeheader()
        for r in result:
            writer.writerow(r)