为什么我在这个Python代码中得到一个KeyError?

2024-10-01 09:30:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着运行这个代码:

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])

我一直收到以下错误:

^{pr2}$

为什么会出现这个错误?在


Tags: oftheto代码namevaluemy错误
2条回答

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

请尝试使用dictVar['PI']

不要使用不存在的钥匙。在

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

相关问题 更多 >