How do I convert this list of dictionaries to a csv file?

backus picture backus · Jun 21, 2010 · Viewed 135.1k times · Source

I have a list of dictionaries that looks something like this:

toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]

What should I do to convert this to a csv file that looks something like this:

name,age,weight
bob,25,200
jim,31,180

Answer

Matthew Flaschen picture Matthew Flaschen · Jun 21, 2010
import csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'w', newline='')  as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(toCSV)

EDIT: My prior solution doesn't handle the order. As noted by Wilduck, DictWriter is more appropriate here.