繁体   English   中英

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

[英]Why didn't I get a key error when the key does not exist?

假设我有一个空的字典。

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM