Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Stumbled upon "'DictReader' object is not subscriptable"

I have no idea what this error is caused by, or how to fix it.

Basically, what I try to achieve is to read from a .csv file and make a dictionary from the information inside it. I've done it before without any problems, but this time it's really weird.

#Read External Data
DataNames = os.listdir("Data")

#Import Classes
ClassesPath = os.path.join("Data", DataNames[1])
Classes = open(ClassesPath)
global ClassesDict
ClassesDict = csv.DictReader(Classes, delimiter=",")

Upon trying to run

print(ClassesDict)

or

print(ClassesDict["ID"])

it always give me the error:

TypeError: 'DictReader' object is not subscriptable

I do know that lists, dictionaries, etc. are subscriptable objects, but my variable "ClassesDict" is (or should be) a dictionary.

Thank you very much in advance.

like image 781
Medallyon Avatar asked Apr 06 '15 21:04

Medallyon


1 Answers

csv.DictReader class provides an iterable interface over the csv data source where items are dictionaries:

reader = csv.DictReader(Classes, delimiter=",")
for row in reader:
    print(row["ID"])
like image 174
alecxe Avatar answered Sep 19 '22 02:09

alecxe