I wrote a function that serializes a list of dictionaries as a CSV file using the CSV module. I sometimes want to write out to a file only a subset of each dictionary's keys however. I use the following code:
def dictlist2file(dictrows, filename, fieldnames, delimiter='\t',
lineterminator='\n'):
out_f = open(filename, 'w')
# Write out header
header = delimiter.join(fieldnames) + lineterminator
out_f.write(header)
# Write out dictionary
data = csv.DictWriter(out_f, fieldnames,
delimiter=delimiter,
lineterminator=lineterminator)
data.writerows(dictrows)
out_f.close()
If I pass in "fieldnames" a subset of the keys that each dictionary has, I get the error:
"dict contains fields not in fieldnames"
How can I make it so that DictRows will write just a subset of the fields I specify to CSV, ignoring those fields that are in the dictionary but not in fieldnames?
thanks.