Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exception is thrown when key is not found in Python dictionary?

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. =(

like image 702
sivabudh Avatar asked Nov 17 '10 18:11

sivabudh


People also ask

What happens if key is not in dictionary Python?

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.

What does the get () method return when a key is not found in the dictionary none KeyError dictionary list of keys?

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 key error exception in Python?

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 specific key is not found in the dictionary?

What does the get method do if the specified key is not found in the dictionary? It returns a default value.


1 Answers

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' >>>  
like image 110
fabrizioM Avatar answered Sep 23 '22 04:09

fabrizioM