开发者

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

开发者 https://www.devze.com 2023-02-07 18:47 出处:网络
My CSV file is 200 Service The开发者_Python百科 code I\'m putting into the interpreter is snav = csv.DictReader(open(\"screennavigation.csv\"), delimiter=\',\')

My CSV file is

200
Service

The开发者_Python百科 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.


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.)


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']

0

精彩评论

暂无评论...
验证码 换一张
取 消