You can use a python dictionary to lookup a value by names. To do this, just do dictionary.get(key)
, where dictionary is your dictionary variable and key is the thing you want to lookup. From your example:
dic.get('John')
would return 123
, and dic.get('Adam')
doesn't return anything.
Checkout this modified example to see. Also a quick side note, its generally bad practice to name both variables in a for loop the same thing. You also need to decide if you're looking for the password in the auth dictionary, or in the regular users dictionary. In my example I checked both.
if requested_name in dic.keys():
print (f'Hello {requested_name}')
elif requested_name in auth.keys():
print('Hello Admin, Take Control')
else:
print ('Wrong Username')
break
for pwd in req_password:
if pwd == dic.get(request_name):
print('Access Granted')
elif pwd == auth.get(request_name):
print('Admin Access Granted')
else:
print('Access Denied')
As a note aside from your original question, there's some things you can do to make the input code a little cleaner. At the start, when you get your input, you do:
requested_name = [input('Name : ').title()]
req_password = [int(input('Password: '))]
The []
Around these are making requested_name be a list of length one, instead of just the variable. Think about x = 3
and how that's different to x = [3]
. The second one make a list with three inside.
I went ahead and modified your code a little bit:
req_name = input('Name : ').title()
req_password = int(input('Password: '))
dic = {'John':123,'Mike':32}
auth = {'Admin': 142}
if req_name in dic.keys():
# If we're in this block, it means this might be a regular user
if req_password == dic.get(req_name):
# Regular username, with correct password
print(f'Hello {req_name}')
print('Access Granted')
else:
# Regular username, but incorrect password
print(f'Sorry {req_name}, Access Denied')
elif req_name in auth.keys():
# If we're in this block, it means this might be an admin
if req_password == auth.get(req_name):
# Auth username with correct password
print(f'Hello {req_name} take control')
print('Access Granted')
else:
# Auth username with incorrect password
print(f'Sorry {req_name}, Access Denied')
else:
print('Wrong Username')
Notice how since we changed those first two lines, we don't need those for
statements anymore. Also, since we want to use different lists for checking the password, depending on which the username is in, we can put the password checking code in with the username checking code.