简体   繁体   English

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

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

Assume I have an empty dict.假设我有一个空的字典。

test_dict = {}

My original code is like this.我原来的代码是这样的。

x = input()
try:
    info = test_dict.get(x)

except:
    print("Key Does Not Exist!")

but it doesn't raise a KeyError in my console, instead, it returns None.但它不会在我的控制台中引发 KeyError,而是返回 None。 I am very sure I tested it and it works but after I updated my Spyder from 4.1.2 to 4.1.5, it doesn't work any more and I have to change my code to this:我很确定我测试了它并且它可以工作,但是在我将 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!")

Why does it return None instead of KeyError?为什么它返回 None 而不是 KeyError?

If you do not understand some behavior help can often be useful.如果您不了解某些行为, help通常很有用。 In this case you can do:在这种情况下,您可以执行以下操作:

test_dict = {}
help(test_dict.get)

to become aware that:意识到:

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