Using some help from the internet, I construct a generic function that extracts specific columns from a csv file and reads it to a dictionary, specified by the input keys.
import csv
def dict_filter(it, keys):
for d in it:
yield dict((k, d[k]) for k in keys)
Then I call this method later to write these columns into another CSV file using DictReaderand DictWriter:
fieldnames = ["_STATE", "HEIGHT", "WEIGHT", "_BMI", "AGE", "CTYCODE", "IYEAR"]
source = open("data88.csv", 'r')
reader = csv.DictReader(source)
result = open("aggregate_data.csv", 'w')
writer = csv.DictWriter(result, fieldnames, extrasaction='ignore')
for d in dict_filter(reader, fieldnames):
if d['_STATE'] == "17" :
writer.writerow(str(d))
Here’s the error I get in terminal:
AttributeError: 'str' object has no attribute 'get'
In TextWrangler:
Traceback (most recent call last): writer.writerow(str(d))
I’ve looked all over the internet and am not finding any relief. Why is writerow not working on my instance of DictWriter?
Change the line
to