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 "To avoid KeyError, use try ... except ... structure:", line 1, in KeyError: '2'
>>> try: ... x = d['2'] ... except KeyError: ... print ("Key 2 is not exist!") ...
Key 2 is not exist!