Why does csv.DictReader give me an attribute error?

My CSV file

200
Service

The code that I put in the interpreter

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 I DictReadershould have returned the dictionary. I suspect I am missing something atrocious.

+3
source share
2 answers

snavthe object is an DictReaderinstance and should not be used as a dictionary. At the iteration, it produces dictionaries that can be accessed accordingly: you needline['200']

+3
source

DictReadercreates a list of dictionaries. Each line in itself is a dictionary - as you show when you repeat in a for loop.

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

+4
source

Source: https://habr.com/ru/post/1789285/


All Articles