Python Tips - Saving Time and Effort with CSVDictWriter and defaultdict
Python’s CSVDictWriter is a handy module that allows you to write dictionary data directly into a CSV file. Here’s how you can use it:
import csv
with open('my.csv', 'w') as csvf:
writer = csv.DictWriter(csvf, fieldnames=[
'field_1',
'field_2',
'field_3'
])
writer.writeheader()
writer.writerow({'field_1': '', 'field_2': 'b', 'field_3': ''})
writer.writerow({'field_1': '', 'field_2': 'b', 'field_3': ''})
While CSVDictWriter is convenient, it stops if any fields in a row are missing. This can be a hassle if you have many fields, and not all of them have values. Do you really need to manually fill in every single field?
Actually, you can solve this problem by using defaultdict.
Posted on Sep 2, 2016 in Python Programming - Intermediate Level by Amo Chen ‐ 1 min read