Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用输入在字典中查找键并将值分配给该变量_Python_Dictionary - Fatal编程技术网

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