zhou
zhou

Reputation: 25

how to get corresponding value in CSV through a list

here is my problem, I tend to get corresponding value in CSV through a list. For example:

I have a list like

namelist=[1,2]

and csv like

name    id    value
 1       a     aaa
 2       b     bbb
 3       c     ccc

and i tend to using every element in the list to find corresponding value in CSV. such as: 1-aaa;2-bbb. this is what i tried now:

with open('1.csv','rb') as f:
reader = csv.DictReader(f)
for i in namelist:
    for row in reader:
        if row['name'] == namelist[i]: 
            print row['value']

but I got nothing. how can i fix it? Thanks in advance!

Upvotes: 1

Views: 229

Answers (2)

Vasily  Bronsky
Vasily Bronsky

Reputation: 433

First of all you should use indents after "with" clause. And another thing that can cause problem may be in this part of code:

for i in namelist:  # in that case if namelist = [1,2] i will be 1 or 2, but you need 0,1

Also you can try this solution if the order of the columns is always such (i mean name,id,value):

namelist=[1,2]

with open('1.csv','rb') as f:
    reader = list(csv.reader(f))
    for row in reader:
        for i in range(len(namelist)): # or if row[0] in namelist: 
            if row[0] == namelist[i]:
            print row[2]

Upvotes: 0

Neil
Neil

Reputation: 14321

A couple things:

  1. csv.DictReader reads items to a dictionary of string:string, not string:int. So, I changed your namelist to a list of strings. Alternatively, you could convert row['name'] to an integer, but I figured it would be more versatile converting your namelist in this manner.

  2. It would be much faster to just check if row['name'] in namelist: then to loop over the entire csv file for every element in namelist.

Code:

import csv

namelist=['1','2']
with open('1.csv','rb') as f:
    reader = csv.DictReader(f)
    for row in reader:
        if row['name'] in namelist: 
            print row['value']

Output:

aaa
bbb

Upvotes: 0

Related Questions