关于python:我可以使用if语句检查字典列表中的值吗?

Can I use an if statement to check that a value is in a dictionary list?

本问题已经有最佳答案,请猛点这里访问。

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

例子:

1
2
3
4
5
6
7
dictionary = {'a': 1, 'b': 2, 'c': 3}

chosen = raw_input("choose one:")

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

当我运行类似这样的程序时,总是默认使用else子句。为什么会这样?


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

1
2
3
4
5
6
7
8
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.