Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write a list of ordered dictionaries to a csv file in python [closed]

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.

like image 728
CLJ Avatar asked Oct 14 '13 19:10

CLJ


People also ask

Can a Python dictionary be saved as a CSV file?

Use csv module from Python's standard library. Easiest way is to open a csv file in 'w' mode with the help of open() function and write key value pair in comma separated form. The csv module contains DictWriter method that requires name of csv file to write and a list object containing field names.

How do I close a CSV file in Python?

Close a CSV FileUse the close() function to close an open file.

Which function is used to write a dictionary into a CSV file?

DictWriter. writeheader() is used to write a row of column headings / field names to the given CSV file.


1 Answers

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.

like image 143
Kirk Strauser Avatar answered Oct 26 '22 19:10

Kirk Strauser