2016-03-10 134 views
0

我有一本字典,像這樣,從用戶輸入打印值

replies = {'0':'Leave it out to dry for 24 hours, if it does not work see customer service', 
      '1':'Go to a repair store to get it fixed', 
      '2':'Charge the phone battery', 
      '3':'Try resetting the phone', 
      '4':'Check to see if something blocking the audio jack or the speakers', 
      } 

我有int(input(,,我希望用戶輸入一個數字,從字典打印出來的價值,我想print(replies[number the user input])

但它不工作,任何幫助表示讚賞,也不是我不是很有經驗,所以簡單有幫助,謝謝

+1

print(回覆[str(數字用戶輸入)]) –

回答

0

如果你想使用數字(整數)作爲關鍵你需要有你的數據這個:

replies = {0: 'Leave it out to dry for 24 hours, if it does not work see customer service', 
      1: 'Go to a repair store to get it fixed', 
      2: 'Charge the phone battery', 
      3: 'Try resetting the phone', 
      4: 'Check to see if something blocking the audio jack or the speakers', 
      } 

在這種情況下,它可能會更好地使用列表並通過索引訪問數據。

0
replies = {'0':'Leave it out to dry for 24 hours, if it does not work see customer service', 
       '1':'Go to a repair store to get it fixed', 
       '2':'Charge the phone battery', 
       '3':'Try resetting the phone', 
       '4':'Check to see if something blocking the audio jack or the speakers', 
       } 

您的索引不是整數,這就是爲什麼你可以說打印回覆[1]

只是改變你的字典

replies = {0:'Leave it out to dry for 24 hours, if it does not work see customer service', 
      1:'Go to a repair store to get it fixed', 
      2:'Charge the phone battery', 
      3:'Try resetting the phone', 
      4:'Check to see if something blocking the audio jack or the speakers', 
      } 
+0

您的索引不是整數,這就是爲什麼您不能說打印回覆[1] * –

0

這一個是工作....試試這個。 。

input1=raw_input("Enter number ") 
print replies[input1] 

您正試圖轉換輸入鍵爲整數....但回覆字典鍵是字符串....