为什么在这段Python代码中会出现KeyError?

为什么在这段Python代码中会出现KeyError?,python,keyerror,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): Fil

我正在尝试运行以下代码:

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
回溯(最近一次呼叫最后一次):
文件“C:/Users/kitkat21266/Google Drive/Project Environment/From 0 to 1 Python Programming/Dictionary and If Else.py”,第8行,在
打印(“与键“+str(3.14)+”对应的值为:“+dictVar[3.14]”)
关键错误:3.14

为什么会发生此错误?

您正在尝试打印dictVar[3.14],但字典中没有键3.14


相反,尝试使用dictVar['PI']

不要使用不存在的键

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

错误很明显,您没有名为
3.14
的键,您有
'PI'
25
“Weihan”
请在此试用代码格式化工具。对于非常短的代码段,我们有
内联格式
,对于块,我们有块格式。有人刚刚为你重新格式化了你的帖子,但如果你能做到这一点,那就省去了别人的工作。谢谢在dictVar 3.14中,是与键“PI”对应的值。它本身不是一个键。嗨,我想“PI”:3.14其中“PI”是键@halfer抱歉忘记了格式。是的,“PI”是键。那么你为什么要用“3.14”作为键呢?嗨,在上面的代码行中,我收到一个TypeError:必须是str,而不是float。(我必须在字典中使用str(3.14)吗?@KitKatOverwatch My bad.have edited.忘了添加
str()
调用。你不能直接将浮点数连接到字符串。你为什么在
print
调用中使用
+
字符串连接?只需将数据作为单独的参数传递并让print处理连接。
print>print(“与键“,”PI'”相对应的值是:“,dictVar['PI'])
。如果需要更多控制,可以使用
格式。好主意。更好的是,我使用了格式化功能。