2

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())
Shaido
  • 27,497
  • 23
  • 70
  • 73
Jay Keuren
  • 37
  • 4
  • `print(logins[logging])`…? – deceze Feb 03 '21 at 06:36
  • @deceze He needs to sanitize for valid inputs – Girish Srivatsa Feb 03 '21 at 06:40
  • Does this answer your question? [Check if a given key already exists in a dictionary](https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary) – Girish Srivatsa Feb 03 '21 at 06:40
  • A quick note for you: when you write "for logging in logins," it means you are iterating through the keys of the dictionary. So, in the first run of the loop, one of the keys of the dictionary will be assigned to the variable "logging". Therefore, logging doesn't contain the input- provided by the user- any more. – Nima S Feb 03 '21 at 06:43
  • BTW, `logging` is a bad name for that variable. First the username has nothing to do with logging, and second there is the [`logging` module](https://docs.python.org/3/library/logging.html) in the Python Standard Library. – Matthias Feb 03 '21 at 07:29

3 Answers3

6

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

    
marmeladze
  • 6,468
  • 3
  • 24
  • 45
4

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

mhawke
  • 84,695
  • 9
  • 117
  • 138
1

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])
DhakkanCoder
  • 794
  • 3
  • 15