Python – Str Attribute has no keys when trying to write dictionary to a CSV file

csvdictionarypython

I am trying to write a dictionary into a CSV file using the following code:

def condense_data(in_file, out_file, city):
"""
This function takes full data from the specified input file
and writes the condensed data to a specified output file. The city
argument determines how the input file will be parsed.

HINT: See the cell below to see how the arguments are structured!
"""

with open(out_file, 'w') as f_out, open(in_file, 'r') as f_in:
    # set up csv DictWriter object - writer requires column names for the
    # first row as the "fieldnames" argument

    out_colnames = ['duration', 'month', 'hour', 'day_of_week', 'user_type']        
    trip_writer = csv.DictWriter(f_out, fieldnames = out_colnames)
    trip_writer.writeheader()

    ## TODO: set up csv DictReader object ##
    trip_reader = csv.DictReader(f_in)

    # collect data from and process each row
    for row in trip_reader:
        # set up a dictionary to hold the values for the cleaned and trimmed
        # data point
        new_point = {}

        ## TODO: use the helper functions to get the cleaned data from  ##
        ## the original data dictionaries.                              ##
        ## Note that the keys for the new_point dictionary should match ##
        ## the column names set in the DictWriter object above.         ##

        duration = duration_in_mins(row, city)
        month, hour, day_of_week = time_of_trip(row, city)
        user_type = type_of_user(row, city)
        new_point = {'duration': duration, 'month': month, 'hour': hour,
                     'day_of_week': day_of_week, 'user_type': user_type}



        print(new_point) # Works fine till here, I am able print the right output
        trip_writer.writerows(new_point) # throws an error

Below is the error that is being thrown:

AttributeError Traceback (most recent call
last) in ()
8
9 for city, filenames in city_info.items():
—> 10 condense_data(filenames['in_file'], filenames['out_file'], city)
11 print_first_point(filenames['out_file'])

in condense_data(in_file, out_file,
city)
38 ## see https://docs.python.org/3/library/csv.html#writer-objects ##
39 print(new_point)
—> 40 trip_writer.writerows(new_point)
41
42

/opt/conda/lib/python3.6/csv.py in writerows(self, rowdicts)
156
157 def writerows(self, rowdicts):
–> 158 return self.writer.writerows(map(self._dict_to_list, rowdicts))
159
160 # Guard Sniffer's type checking against builds that exclude complex()

/opt/conda/lib/python3.6/csv.py in _dict_to_list(self, rowdict)
146 def _dict_to_list(self, rowdict):
147 if self.extrasaction == "raise":
–> 148 wrong_fields = rowdict.keys() – self.fieldnames
149 if wrong_fields:
150 raise ValueError("dict contains fields not in fieldnames: "

AttributeError: 'str' object has no attribute 'keys'

I did look it this type of questions on Stack Overflow but none of them helped.

Best Answer

You're using writerows() where you should use writerow(), because you're trying to write one row, not a list of them.