user11589714
user11589714

Reputation:

Unable to search a record in list in list

With the help of some contributors from StackOverflow, I wrote a small program to read in a CSV file so that I could search a record or multiple records. The program works and is tested but when it reads from a CSV file, it does not work. I try to search a record in the list of list and it fails to find anything. Could someone help please?

import csv

#Read in CSV file
datafile = open('nba_2Records.csv', 'r')
datareader = csv.reader(datafile, delimiter=';')
data = []
for row in datareader:
    data.append(row)    

print(f"Data = {data}")

# Search Value
search = 'Boston Celtics'

for sublist in data:

    print(f"sublist : {sublist}")
    if search in sublist:
        print("Found it!" + str(sublist))
    else:
        print("Not found")


=============================================================================================================================
Data = [['Name,Team,Number,Position,Age,Height,Weight,College,Salary'], ['Avery Bradley,Boston      Celtics,0,PG,25,2-Jun,180,Texas,7730337'], ['Jae Crowder,Boston Celtics,99,SF,25,6-Jun,235,Marquette,6796117']]
sublist : ['Name,Team,Number,Position,Age,Height,Weight,College,Salary']
Not found
sublist : ['Avery Bradley,Boston Celtics,0,PG,25,2-Jun,180,Texas,7730337']
Not found
sublist : ['Jae Crowder,Boston Celtics,99,SF,25,6-Jun,235,Marquette,6796117']
Not found

Upvotes: 0

Views: 26

Answers (2)

Rakesh
Rakesh

Reputation: 82765

You need to use the delimiter as ,

Ex:

search = 'Boston Celtics'

with open('nba_2Records.csv') as datafile:
    datareader = csv.reader(datafile, delimiter=',')
    next(datareader) #Skip header
    for row in datareader:
        if search in row:
            print("Found it! " + row)

Upvotes: 0

Dev Khadka
Dev Khadka

Reputation: 5451

your sublist is array with only one string item, when using string in list it will search for list item equal to the string not for list item containing in the string.

If you always have one element on sublist the you can do this

if search in sublist[0]:
        print("Found it!" + str(sublist))

Else you have to add another loop

for item in sublist:
    if search in item:
        print("Found it!" + str(item))

Upvotes: 1

Related Questions