2017-06-05 142 views
-3

我試圖運行此代碼:爲什麼我在這個Python代碼中得到一個KeyError?

dictVar = {'PI': 3.14, 
      25: "The Square of 5", 
      "Weihan": "My Name" 
      } 

print("The value corresponding to the key " + str(3.14) + " is: " + dictVar[3.14]) 

我不斷收到以下錯誤:

Traceback (most recent call last): 
    File "C:/Users/KitKat#21266/Google Drive/Project Environment/From 0 to 1 Python Programming/Dictionary and If-Else.py", line 8, in <module> 
    print("The value corresponding to the key " + str(3.14) + " is: " + dictVar[3.14]) 
KeyError: 3.14 

爲什麼會出現這種錯誤發生的呢?

+3

錯誤是明確的,你有沒有名爲鍵'3.14',你有''PI'','25'和'‘胃寒’' – EdChum

+0

請花一點時間來這裏嘗試一下代碼格式化工具。對於非常短的代碼,我們有'inline formatting',並且塊的格式化。剛纔有人爲你重新格式化了你的文章,但是如果你能做到這一點,那麼它可以節省工作的人。謝謝! – halfer

+0

在dictVar 3.14中是與'PI'對應的值。這本身並不是一個關鍵。 –

回答

1

不要使用不存在的鑰匙。

key = "PI" 
print("The value corresponding to the key {0} is: {1}".format(key, dictVar[key])) 
+0

嗨與上面的代碼行我收到TypeError:必須是str,而不是浮動。 (我是否需要str(3.14)在dictironary中? –

+0

@KitKatOverwatch我的錯誤,編輯過。忘了添加一個'str()'調用。你不能連接浮點數到字符串。 –

+0

它的工作!非常感謝! –

1

您正在嘗試打印dictVar [3.14],但字典中沒有鍵3.14。

而是嘗試使用dictVar [ 'PI']

相關問題