Python 使用输入在字典中查找键并将值分配给该变量
所以,我现在有这个代码Python 使用输入在字典中查找键并将值分配给该变量,python,dictionary,Python,Dictionary,所以,我现在有这个代码 potions ={"small_health":15, "small_instant_exp":250} selection = input("Pick one") 如果选择项与用户选择的键具有相同的名称,如何使其具有相同的值?使用potitions.get(),并将输入作为参数 potions = {"small_health": 15, "small_instant_exp": 250} selection = potions.get(input("Pic
potions ={"small_health":15, "small_instant_exp":250}
selection = input("Pick one")
如果选择项与用户选择的键具有相同的名称,如何使其具有相同的值?使用potitions.get(),并将输入作为参数
potions = {"small_health": 15, "small_instant_exp": 250}
selection = potions.get(input("Pick one"))
您可以在无限
while
循环中使用try except
块。这将持续接收用户的输入,直到用户输入正确的输入(与药剂中的键匹配的输入)
因此,如果输入为“small_health”,那么selection
应设置为15?此外,如果输入与dict中的任何内容都不匹配,该怎么办?它将处于while循环中,直到选择了正确的选项,但您得到了正确的想法。
potions = {"small_health": 15,
"small_instant_exp": 250}
while True:
try:
selection = potions[input("Pick one")]
print(selection)
break
except:
print('Wrong Input')