为什么我在这个 Python 代码中得到一个 KeyError?
Why do I get a KeyError in this Python code?
我正在尝试 运行 此代码:
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
为什么会出现这个错误?
您正在尝试打印 dictVar[3.14],但您的字典中没有关键字 3.14。
改为尝试使用 dictVar['PI']
不要使用不存在的密钥。
key = "PI"
print("The value corresponding to the key {0} is: {1}".format(key, dictVar[key]))
我正在尝试 运行 此代码:
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
为什么会出现这个错误?
您正在尝试打印 dictVar[3.14],但您的字典中没有关键字 3.14。
改为尝试使用 dictVar['PI']
不要使用不存在的密钥。
key = "PI"
print("The value corresponding to the key {0} is: {1}".format(key, dictVar[key]))