简体   繁体   中英

How can a dictionary key be called without hardcoding references in the code like ie. if/else statements (with entry/input)?

d = {
    'key1': 'value1',
    'key2': '12345',
    'anotherKey': 'anotherValue',

}


for x in d.items():
    ans = input("Enter dict key")
    if ans in d:
        print("The key to {key} is {value}s".format(key=ans))
    if ans == ('key1'):
        print(d)
        
    else:
            print("It is not in the dictionary")

This example with a for loop is just an example. I have worked with if/else statements and a working widget with entries but with a horrible code where every new variable had to be added in multiple places. It is therefore my goal now to grab keys in the dictionary from the input exclusively, not by hardcoding alternatives into the code. I am a bit amazed it is not more obvious for a beginner to get the input statement to pick a key and present its value. If theres another way of handling the issue instead of dict, I am all ears.

Just do value=d[ans] in the format string Like this:

d = {
    'key1': 'value1',
    'key2': '12345',
    'anotherKey': 'anotherValue',

}


for x in d.items():
    ans = input("Enter dict key")
    if ans in d:
        print("The key to {key} is {value}s".format(key=ans, value=d[ans]))
        
    else:
        print("It is not in the dictionary")

Simply use

>>> d={...}
>>> print(d.get('key_name'))

To get the value from key

d = {
    'ebay': 'lösenord',
    'discogs': '12345',
    'banken': 'jättehemligt',
    'a': 'skithemligt',

}


for x in d.items():
    ans = input("Enter dict key")

    value=d[ans]

    print(d.get(ans))

Ps. I know working with passwords in this way is not recommended but that is another story:). Hashing and encryption coming up and that paper on the desk never before looked so appealing for passwords.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM