write a list of ordered dictionaries to a csv file in python

CLJ picture CLJ · Oct 14, 2013 · Viewed 7.5k times · Source

After reading a CSV file using

with open(filename, 'r') as f:
  reader = csv.DictReader(f)
  for line in reader:
    date = line['Date']

each line is an OrderedDict

OrderedDict([
    ('Date', '2008-03-20'), 
    ('Name', 'Some name'),...)
])

I would like to write this list of ordered dictionaries to a csv file in python using the keys of the first dictionary in the list as the column header.

Answer

Kirk Strauser picture Kirk Strauser · Oct 14, 2013

Use a csv.DictWriter object to do all the heavy lifting for you:

import csv
with open('spreadsheet.csv', 'w') as outfile:
    fp = csv.DictWriter(outfile, list_of_dicts[0].keys())
    fp.writeheader()
    fp.writerows(list_of_dicts)

It creates a new CSV, writes a header line to it so you know what each column represents, then writes out each dict as a row with all the columns in the same order as the header column.