2017-06-05 144 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']

相关问题