简体   繁体   中英

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. 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:

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?

If you do not understand some behavior help can often be useful. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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