Riazm
Riazm

Reputation: 365

Why is csv.DictReader giving me a no attribute error?

My CSV file is

200
Service

The code I'm putting into the interpreter is

snav = csv.DictReader(open("screennavigation.csv"), delimiter=',')
print snav.fieldnames
['200']

for line in snav:
...     print(line)
...
{'200': 'Service'}

snav["200"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: DictReader instance has no attribute '__getitem__'

I thought that DictReader was meant to return a dictionary. I suspect I'm missing something brutally obvious.

Upvotes: 4

Views: 12087

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599638

The DictReader produces a list of dictionaries. Each line is itself a dictionary - as you show when you iterate through in your for loop.

(OK, it's actually an iterable, not a list, but the point stands.)

Upvotes: 4

SilentGhost
SilentGhost

Reputation: 319701

snav object is DictReader instance and shouldn't be accessed as a dictionary. On iteration it produces dictionaries that could be accessed accordingly: you need line['200']

Upvotes: 3

Related Questions