【问题标题】:Can I use an if statement to check that a value is in a dictionary list? [duplicate]我可以使用 if 语句来检查字典列表中的值吗? [复制]
【发布时间】:2017-04-09 00:43:41
【问题描述】:

我想让用户使用输入从字典中调用变量,但我想要一种方法来检查该值是否不存在。

示例:

dictionary = {'a': 1, 'b': 2, 'c': 3}

chosen = raw_input("choose one:")

if(dictionary[chosen] == true):
   print(chosen)
else: print("Invalid choice")

当我运行这样的事情时,总是默认使用else 子句。这是为什么呢?

【问题讨论】:

  • if chosen in dictionary:
  • youve no : after your if statement and == true 是不必要的,true 也应该是 True
  • 我写这个作为一个例子,只是为了展示我正在尝试做的事情,如果可能的话,我一直在寻找关于如何做到这一点的理论。谢谢!
  • 如果您更正代码中的错误,只要用户输入密钥而不是值,它就可以工作
  • 你的意思是检查一个键是否在字典中?在这种情况下,这是Python: how can I check if the key of an dictionary exists? 的重复。如果不是这样,那么不清楚你在问什么。

标签: python


【解决方案1】:

如果您清除语法错误并使用 in 关键字,您的代码可以正常工作:

dictionary = {'a': 1, 'b': 2, 'c': 3}

chosen = raw_input("choose one:")

if chosen in dictionary: #added colon and changed to if chosen in dictionary
    print(chosen + " : " + str(dictionary[chosen])) #changed to bring both key and value because I didn't know which you wanted
else:
    print("Invalid choice") #I added a new line.

【讨论】:

    猜你喜欢
    • 2020-04-12
    • 2013-10-05
    • 1970-01-01
    • 2018-09-09
    • 2015-12-06
    • 2019-07-23
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    相关资源
    最近更新 更多