首页 > 解决方案 > 如何在没有硬编码引用的情况下调用字典键,例如 ie。if/else 语句(带有条目/输入)?

问题描述

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,我会全神贯注。

标签: pythonpython-3.6

解决方案


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

附言。我知道不建议以这种方式使用密码,但这是另一回事:)。散列和加密技术出现了,桌上的那张纸对密码来说从未如此吸引人。


推荐阅读