问题描述
假设我有一个空字典。
test_dict = {}
我的原始代码是这样的。
x = input()
try:
info = test_dict.get(x)
except:
print("Key Does Not Exist!")
,但它不会在我的控制台中引发KeyError,而是返回None。我非常确定我已经对其进行了测试,但是我将Spyder从4.1.2更新到4.1.5后,它不再起作用,因此我必须将代码更改为此:
x = input()
if x in test_dict.keys():
info = test_dict.get(x)
else:
print("Key Does Not Exist!")
为什么它返回None而不是KeyError?
解决方法
如果您不了解某些行为,help
通常会很有用。在这种情况下,您可以执行以下操作:
test_dict = {}
help(test_dict.get)
意识到:
Help on built-in function get:
get(key,default=None,/) method of builtins.dict instance
Return the value for key if key is in the dictionary,else default.