Issue
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?
Solution
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.
Answered By - Daweo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.