如果不在代码中硬编码引用,如 ie,如何调用字典键。 if/else 语句(entry/input)?

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")

这个带有 for 循环的例子只是一个例子。我使用过 if/else 语句和一个带有条目的工作小部件,但代码很糟糕,每个新变量都必须添加到多个地方。因此,我现在的目标是专门从输入中获取字典中的键,而不是通过将备选方案硬编码到代码中。我有点惊讶,对于初学者来说,让输入语句选择一个键并显示它的值并不是更明显。如果有另一种处理问题的方法而不是 dict,我洗耳恭听。

在格式字符串中做value=d[ans] 像这样:

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")

简单使用

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

获取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。我知道不建议以这种方式使用密码,但那是另一回事 :)。散列法和加密技术即将问世,桌上的那张纸对密码的吸引力从未如此大。