If I have:
map = { 'stack':'overflow' } try: map['experts-exchange'] except: <--- What is the Exception type that's thrown here? print( 'is not free' )
Couldn't find it on the web. =(
If given key does not exists in dictionary, then it returns the passed default value argument. If given key does not exists in dictionary and Default value is also not provided, then it returns None.
get() method returns a default value if the key is missing. However, if the key is not found when you use dict[key] , KeyError exception is raised.
What is Python KeyError Exception? Python KeyError is raised when we try to access a key from dict, which doesn't exist. It's one of the built-in exception classes and raised by many modules that work with dict or objects having key-value pairs.
What does the get method do if the specified key is not found in the dictionary? It returns a default value.
KeyError
if you do it on the console without the try block will tell it to you
>>> a = {} >>> a['invalid'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'invalid' >>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With