Reputation: 397
I want to create a python lookup function for students. I have a tab delimited file with ID and students name. I want to create a lookup program such that entering either a student's name or ID will return name of the student and student ID if a match has been found.
So far I have imported the data successfully. Snippet of data is shared. Having trouble defining a function. I am sharing my code below:
infile = open("D:/work/student_id.txt", "r")
def lookup():
word =raw_input("code to lookup: ")
print ("\n")
n = elements.index(word)
x = elements[n][0]
y = elements[n][0]
if word == x:
print x, ":", y, "\n"
else:
print("That code does not exist")
lookup()
I searched online(stackoverflow-found post by Erik and Alexander, I tried to model my code like theirs but still no help; O'riley books on Python) for help regarding creation of lookup function but they all involved writing the data out. But I found no guidance on creating a lookup function for an imported tab delimited file. I hope this will help others as well. Any advice?
Upvotes: 0
Views: 555
Reputation: 2533
What version of Python are you using?
Python 3 uses input()
, not raw_input()
.
As your file is tab-separated you can use the csv function.
import csv
students = {}
search = input()
found = None
with open('student_id.txt', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
for row in reader:
students[row[0]] = row[1]
print(students)
for i in students.keys():
if search == i:
found = search + " " + students[i]
else:
if search == students[i]:
found = i + " " + students[i]
if found == None:
print("Not found")
else:
print(found)
Upvotes: 2