Dictionaries, call value from key

Viewed 94

I am trying to grab input and if the dictionary logins has a key that matches my input, I want to return the value of that key.

logins = {
    'admin':'admin',
    'turtle':'password123'
}

logging = input('username: ')

for logging in logins:
    print(logins.values())
3 Answers

Try this.

logins = {
    'admin':'admin',
    'turtle':'password123'
}

logging = input('username: ')

value = logins.get(logging, "Not found")
print(value)

Thanks to @deceze for kind suggestion

If you need an iteration with for, try

for login in logins:
    #do something with login
    # e.g. if login == input

    

No looping necessary, just lookup by key.

logging = input('username: ')
value = logins.get(logging)
if value is not None:
    print(value)
else:
    print(f"username {logging!r} was not found")

Alternatively:

print(logins[logging])

however this will raise a KeyError exception if the key logging is not in the dictionary

You're on the right path. All you need to do is make use of the native property of dictionary to find if the element is in dictionary:

logins = {
    'admin':'admin',
    'turtle':'password123'
}

logging = input('username: ')

if logging in logins:
  print(logins[logging])
Related