Exceptions
Exceptions
KeyError
If you try to read or pop or delete a key from a dictionary which does not exist, a KeyError
is raised. This is similar to the IndexError
you’ve seen in the cases of lists and tuples.
If you encounter a KeyError
it means the specified key does not exist in the dictionary.
>>> furniture = {'living room': ['armchair', 'sofa', 'table'],
... 'bedroom': ['bed', 'nightstand', 'dresser'],
... 'office': ['desk', 'chair', 'cabinet']}
>>> furniture['kitchen']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'kitchen'
TypeError
If you try to add to a dictionary a key which is not hashable, Python will raise a type error:
>>> d = {[1, 2, 3]: 'cheese'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Unlike IndexError
which is almost always due to a programming error—and thus we do not wish to handle such exceptions—there are cases where we would wish to handle KeyError
should it be raised. This will depend on context.
Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >
No generative AI was used in producing this material. This was written the old-fashioned way.
This material is for free use under either the or the (take your pick).