Python keyerror exception

Python KeyError exception occur when the key is not found in a dictionary.

>>> d = {'1' : 'a', '4' : 'b', '5' : 'c'}
>>> x = d['1']
>>> x
a
>>> x = d['1']
>>> x
b
>>> x = d['2'] #key 2 is not in dictionary d
Traceback (most recent call last):
File "", line 1, in 
KeyError: '2'
To avoid KeyError, use try ... except ... structure:
>>> try:
... x = d['2']
... except KeyError:
... print ("Key 2 is not exist!")
...
Key 2 is not exist!














endmemo.com © 2024  | Terms of Use | Privacy | Home