I'm working on a spin-off project from a Code Academy lesson and running into an error when trying to append a specific column from each row of a CSV to a list.
The code from the lesson:
import csv
with open('cool_csv.csv') as cool_csv_file:
cool_csv_dict = csv.DictReader(cool_csv_file)
for row in cool_csv_dict:
print(row['Cool Fact'])
I need to read in each row from my CSV, and append the value of the "subject" column to the entries list.
import csv
entries = []
with open("list.csv") as list_csv:
list_reader = csv.DictReader(list_csv)
for row in list_csv:
entries.append(row["subject"])
But I'm getting the following error:
entries.append(row[“subject”]) TypeError: string indices must be integers
I get that the error is saying that the value passed by row was a string, so I can’t access it with the header name, but what I don’t get is why. My file is a valid CSV as far as I can see, and my code is no different to that in the lesson other than appending instead of printing (I tested print, same error.)
My CSV:
subject,subject_type
first,test
second,test
What have I done wrong that’s making my code read in a string instead of the csv row?
list_reader, not withlist_csv