我正在尝试运行此代码:
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
为什么会出现此错误?
答案 0 :(得分:1)
您正在尝试打印dictVar [3.14],但字典中没有关键字3.14。
请尝试使用dictVar [&#39; PI&#39;]
答案 1 :(得分:1)
请勿使用不存在的密钥。
key = "PI"
print("The value corresponding to the key {0} is: {1}".format(key, dictVar[key]))