Why KeyError is raised in Python?

The KeyError is raised when you try to access a key in a dictionary that does not exist. For example, consider this simple dictionary:

a_dict = {1:’Hello’,2:’World’, 3:’Python’}

If you try accessing its values by keys then see how it outputs:

As such, 1 and 3 keys exist, it displayed the respective values for those keys. The key 4 does not exist and an error generated KeyError: 4.

So, how to deal with this KeyError exception so that program does not crash even if a key is not available?

How can KeyError Python be avoided to crash a program?

The first way is using the try-except block and handle the KeyError there. You may display a descriptive message if KeyError occurs and the program will not crash.

Have a look at this example where KeyError is handled in try-except:

See online demo and code


In the output figure, you can see the values for first two keys are displayed while key 4 produced an error that was handled in except block.

More practical example of KeyError

In the following example, a small dictionary with only three items is created. The dictionary stores dummy phone numbers with names. The names act as the key while phone numbers as values. As you run the program, it will ask to enter the name.

If the name (key) exists in the dictionary, it will display the phone number, otherwise, except block will catch the KeyError and display a helpful message:

See online demo and code

keyerror get

You see, if you have a large dictionary that requires some user input, you may handle the KeyError easily.

Second way – Using the get method of dictionary

You may also manage the Python keyError exception by using the get method of the dictionary.

  • The get method of the dictionary is used to return the value for the key.
  • If a key does not exist the default is returned.
  • If you do not provide the default, it defaults to None.
  • That is why the KeyError is not raised as using the get method of the dictionary.

See an example below for learning how to use get method with default value:

See online demo and code

keyerror get

In the output graphic, you can see program displayed salaries for emp ID 1 and 3. As I entered 5, it did not raise any exception (KeyError). Instead get method displayed the default message.