Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for value in a sequence in Python?

I am very new to coding so please bear with me. Basically I am writing a program that will ask for either a last name or id number, then search a .csv file for the word and return the entire column to which it belongs. Below is what I have written if the user opts to search by the id.

method = input("Search by invoice id (id) or customer last name (lname)?: ")
    data = "data.csv"
    dataFile = open(data, "r")
    dataRows = dataFile.readlines()

if method == "id":
    term = input("Enter the id: ")
    for line in dataRows:
        row = line.strip()
        newRow = row.split('\n')
        if term == newRow[0]:
            print(newRow)
        else:
            print("No matches found.")

This is the csv file: Here is a photo of the csv file.

This is how it prints out after readlines():

['invoice id,first name,last name,part number,quantity,total']
['111,Jim,Morrison,27,1,50.25']
['222,Ray,Manzarek,25,2,64.46']
['333,John,Densmore,16,4,34.34']
['333,Robby,Krieger,32,2,34.34']
['555,Jim,Morrison,12,4,43.34']
['333,Jim,Morrison,35,2,34.76']
['888,John,Densmore,63,2,34.76']
['111,Robby,Krieger,21,1,64.45']
['458,Freddie,Mercury,32,4,45.23']
['111,Freddie,Mercury,21,1,46.2']
['234,Allie,McGuire,43,3,64.45']
['675,Allie,McGuire,32,4,45.23']
['359,Freddie,Mercury,423,2,34.34']

Since invoice ID is the first column, I thought it would be found by using if term ==newRow[0], but that's not working. Any tips? Thanks so much.

like image 404
Allie M Avatar asked Apr 23 '26 22:04

Allie M


1 Answers

The simplest way to do this is using the csv module:

method = input('Search by invoice id (id) or customer last name (lname)?: ')
term = input('Enter the term: ')

found_row = None     # To store the row if a match is found

with open('data.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)

    for row in reader:
        # Compare term with Invoice ID if chosen method is ID
        # else compare with Last Name
        if term == (row['invoice id'] if method == 'id' else row['last name']):
            found_row = row

if found_row:
    print(row)
else:
    print('No match found')

If you're allowing the user to search by ID or last name only, it's possible to simplify your input even further by asking them to enter 1 for ID and 2 for Last Name. This approach is inflexible but the advantage is that users are less likely to enter the method in wrong case. For example, you're comparing method == 'id' but the user might enter Id or ID. Might make your life a bit simpler.

like image 190
Abhinav Sood Avatar answered Apr 26 '26 12:04

Abhinav Sood