n8o
n8o

Reputation: 1943

python - find specific row attribute with DictReader

I want to find specific row with DictReader.

csv file(test.csv)

numb, firstname, lastname
1, yong, kim
2, gwang, lee
3, geun, lee 
...

.py file

import csv
from collections import defaultdict
from operator import itemgetter

result = {}
result = defaultdict(lambda: 0, result)

tmp = open('test.csv', 'r')
file = csv.DictReader(tmp)

# what I want
print file[1]['firstname'] # => I want it to be : "gwang"

EDIT

When I run this code, below error occurs.

Traceback (most recent call last):
  File "****.py", line 23, in <module>
    print file[1]['firstname']
AttributeError: DictReader instance has no attribute '__getitem__'

What should I do?

cheers!

Upvotes: 0

Views: 6029

Answers (2)

jaqHollow
jaqHollow

Reputation: 84

You need to iterate through the DictReader object you created, i.e file. See this example to understand how one uses the DictReader. Basically you are stepping through the csv row by row

From the docs:

import csv
with open('names.csv') as csvfile:
     reader = csv.DictReader(csvfile)
     for row in reader:
         print(row['first_name'], row['last_name'])

So just use an if to check if the current row you are on matches your search criterea

Upvotes: 2

Sevanteri
Sevanteri

Reputation: 4058

As it is said on the documentation:

Returns a reader object which will iterate over lines in the given csvfile.

You can't access the rows with reader_obj[x] (__getitem__) as it is an iterator.

You first have to materialize the iterator as a list:

tmp = open('test.csv', 'r')
file = csv.DictReader(tmp)
data = list(file)

print data[1]['firstname']

This is of course reads the whole file to RAM which might not be ideal if it is a big file.

It is preferred to just iterate through the reader as it is shown in the documentation.

Upvotes: 3

Related Questions