K. ossama K. ossama - 3 months ago 9
Python Question

How can I get values from dictionary for particular key using python

In this code, I wanted to identify a member with his ID. If the ID exist in the dictionary, I would like to print the fullname of this member

iin = input('Enter your ID :')
dict = {'id' : ['aa', 'bb', 'cc'],
'Firstname' : ['Mark', 'Jamal', 'Van'],
'Lastname' : ['Roch', 'borh', 'nilsa']}
for d in dict:
if inn in d:
print('Hello,', dict[inn])
else :
print('Sorry, you are not a member')


The desired result

Enter your ID : aa
Hello, Mark Roch


Thank you for the help

Answer

Please check the below code with comments inline.

iin = input('Enter your ID :')
d = {'id' : ['aa', 'bb', 'cc'],
        'Firstname' : ['Mark', 'Jamal', 'Van'],
        'Lastname' : ['Roch', 'borh', 'nilsa']}
#Get list of IDs    
id_list = d['id']

#Check input in list
if iin in id_list:
    #Get index of input from ID list
    index = id_list.index(iin)
    #Get rest of info
    fname = d['Firstname'][index]
    lname = d['Lastname'][index]
    msg = "Hello, " + fname + " " + lname
    print msg
else:
    print 'Sorry, you are not a member'

Output :

C:\Users\dinesh_pundkar\Desktop>python b.py
Enter your ID :"aa"
Hello, Mark Roch

C:\Users\dinesh_pundkar\Desktop>python b.py
Enter your ID :"asd"
Sorry, you are not a member

C:\Users\dinesh_pundkar\Desktop>