Skip to content Skip to sidebar Skip to footer

How To Get Value From Dict If Its Key Can Have Several Values

I have a dict with credentials like the following: secret = {'password': 'jdksal', 'user': 'fjdklas', 'schema': 'jfdaskl'} I want to create a variable for pass

Solution 1:

As you have written it, password will get the last match if there is more than one overlap between pass_word and secret. I don't know is that is your intent.

You could use set operations if there is only one overlap:

>>> secret.keys() & pass_words
{'password'}
>>> secret.keys() & user_words
{'user'}

Then to get the value associated with that key:

>>>secret[(secret.keys() & pass_words).pop()]
jdksal
>>>secret[(secret.keys() & user_words).pop()]
fjdklas

For older Pythons that don't have dict set views, just apply set to each for the same result:

>>> set(secret.keys()) & set(user_words)
{'user'}

With Python 3.6+, you can do:

password, user={k:v fork,v in secret.items() if k in pass_words+user_words}.values()

Solution 2:

I Think This Will Be Better:

pass_words = ['password', 'pass', 'contraseƱa']

secret = {"password": pass_words,
          "user": "fjdklas",
          "schema": "jfdaskl"}

input_password = input("Enter Your Password: ")
for key,value in secret.items():
    if input_password in value:
        print("Correct Password")

You Can Change The Input Method As You Like. The Key Variable Will Hold The Key Of The First Item In The Dictionary And The Value Variable Will Hold The Value, Which Will Be A List In Your Case, For The First Item In The Dictionary.

Post a Comment for "How To Get Value From Dict If Its Key Can Have Several Values"