2017-04-09 111 views
-1

我想讓用戶使用輸入從字典中調用變量,但我想要一種方法來檢查值是否不存在。我可以使用if語句來檢查值是否在字典列表中?

例如:

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

chosen = raw_input("choose one:") 

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

當我運行這樣的事情總是默認爲else條款。爲什麼是這樣?

+2

'如果選擇在詞典:'你已 – Wright

+0

沒有':''你聲明if'和'後= = true'是不必要的,同樣'true'應該是'True' – Craicerjack

+0

我寫這個爲例,只是爲了展示我正在嘗試做什麼,我正在尋找理論如何做到這一點,如果可能的話。謝謝! –

回答

0

如果清理語法錯誤和使用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.