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.
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.
Close a CSV FileUse the close() function to close an open file.
DictWriter. writeheader() is used to write a row of column headings / field names to the given CSV file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With