Matthew Willis Matthew Willis - 15 days ago 6
Python Question

python dictionary - how to search and display answers

I'm trying to use a database implemented as a dictionary to search for a user entered value and if that value is found, it is displayed or else an error message is displayed.
'uuc' or 'uum' etc refers to abbreviations for a university campus.

The user should be able to enter one of the above values and any matches should be displayed. However, this doesn't work in my code and I can't locate the problem.

def all_from(datab,university):
l = len(datab)
k = 1
i = 0
while k <= 1:
s = datab[k]
the_university = s[2]
if university == the_university:
i = i + 1
print datab[k]
k = k + 1
if i == 0:
print 'Nobody goes to University there!'

datab = dict()
datab[1] = ['walker','matthew','uuc',1]
datab[2] = ['stewart','rory','uum',2]
datab[3] = ['toner','kevin','qub',4]
datab[4] = ['hughes','johnny','uuj',1]
datab[5] = ['douglas','kenny','uuc', 3]
datab[6] = ['hooks', 'peter','qub',1]
datab[7] = ['campbell','vicky','uuj',2]
datab[8] = ['crooks','laura','uum',4]
datab[9] = ['irwin','emma','uuc',3]
datab[10] = ['patterson','steve','uuc',1]

university = (raw_input('Enter the University here: '))
all_from(datab,university)

Answer

My contribution. I feel that arranging the students as items in a list, with the different fields as dictionary keys is a better data structure.

def find_all(datab,uni):
    for student in datab:
        if student['uni'] == uni:
            print(student)

datab = []
datab.append( {'lastname':'walker', 'firstname':'matthew','uni':'uuc','year':1})
datab.append( {'lastname':'stewart','firstname':'rory','uni':'uum','year':2})
datab.append( {'lastname':'toner','firstname':'kevin','uni':'qub','year':4})
datab.append( {'lastname':'hughes','firstname':'johnny','uni':'uuj','year':1})

uni = input('Enter the uni here: ')
find_all(datab,uni)

If you want to search through all the keys then you could change the if student['uni'] == uni line to

for key, value in student.items():
    if value == uni: