当密钥不存在时,为什么我没有得到密钥错误?

2024-04-25 19:26:15 发布

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

假设我有一张空的字典

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


Tags: key代码testinfononeinputget字典
1条回答
网友
1楼 · 发布于 2024-04-25 19:26:15

如果您不了解某些行为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.

相关问题 更多 >