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:
>>> a_dict[1] 'Hello' >>> a_dict[3] 'Python' >>> a_dict[4] Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> a_dict[4] KeyError: 4
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:
#A demo of avoding KeyError a_dict = {1:'Hello',2:'World', 3:'Python'} try: print(a_dict[1]) print(a_dict[2]) print(a_dict[4]) except KeyError: print("The key does not exist!")
Output:
In the output figure, you can see the values for the 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:
#A demo of KeyError with user input Name = input("Enter a Name? ") tel_dict = {'Hira': 485457454,'Shania': 789456123, 'Jimmy':69699696} try: print("The Telephone of ",Name ,":" ,tel_dict[Name]) except KeyError: print("No Name exist!")
Sample outputs:
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 the 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:
#A demo of KeyError with Dictionary Get emp_id = int(input("Enter Employee ID? ")) salary_dict = {1: '£3000',2: '£3500', 3: '£4000'} sal = salary_dict.get(emp_id,'Wrong Employee ID!') print("The Salary is: " ,sal)
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.