python - 如何在没有硬编码引用的情况下调用字典键,例如 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,我会全神贯注。
解决方案
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))
附言。我知道不建议以这种方式使用密码,但这是另一回事:)。散列和加密技术出现了,桌上的那张纸对密码来说从未如此吸引人。
推荐阅读
- call - 如何处理 IncallService 中的呼叫等待
- flutter - 发布请求后如何处理响应 dart httpClient
- sas - 在 SAS University Edition 中,当使用带有 BINARY 选项的 Proc Corresp 命令时,我得到的答案是“输出数据大于 3MB
- java - 为什么我的代码不断抛出 StringIndexOutOfBoundsException?
- android - 如何在不将其置于前面的情况下启动其他应用程序的活动?
- sql - 单独的 PostgreSQL 分区加入
- scala - Dotty 无法推断具有抽象类型的类型参数特征的通用 Scala 函数的结果类型
- javascript - 裁剪后的图像显示有一个奇怪的 1px 黑色边框
- batch-file - 访问被拒绝在 cmd 中创建文本文件和奇怪的“如果存在”问题
- python - cv2.VideoCapture 无法读取远程视频文件