【问题标题】:Save the KEY only once when a user inputs either the key or value from a dictionary [duplicate]当用户从字典中输入键或值时,只保存一次键[重复]
【发布时间】:2021-06-04 03:42:09
【问题描述】:

因此,当用户输入密钥本身或 python 中的密钥值时,我试图从字典中接收密钥。

dict= {'1':'one','2':'two','3':'three','4':'four','5':'five'}

userinput = input('Please choose from the dictionary : ')    
for key, values in dict.items():
    if userinput == key or values:
        print (key)

所以我在想用户输入“2”时是“2”还是用户输入“5”时是“5”

而是我自己得到了钥匙

【问题讨论】:

  • print(dict[key]) - 另外,不要将您的 dict “dict”称为内部 python 类型。
  • 另外,倒置字典,因为那是你真正想要做的。

标签: python loops dictionary


【解决方案1】:

很遗憾,我们无法像您显示的那样比较变量 if x == y or z。 试试这个

dict= {'1':'one','2':'two','3':'three','4':'four','5':'five'}

userinput = input('Please choose from the dictionary : ')    
for key, values in dict.items():
    if userinput == key or userinput == values:
        print (key)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2020-06-16
    相关资源
    最近更新 更多