Python KeyError: A Complete Guide

Posted in /  

Python KeyError: A Complete Guide
vinaykhatri

Vinay Khatri
Last updated on June 20, 2024

    In Python, keys are used by the dictionary to assign and access values. But if we try to access a dictionary value with an invalid key that does not exist in the dictionary, Python would raise the KeyError.

    In this Python guide, we will discuss the Python KeyError in detail and see how to handle it.

    Handling Python KeyError

    If you are encountering the KeyError in your Python program, it's just because you are trying to access a dictionary value using a key that does not exist. Handling and solving this error in Python is very easy. The most straightforward way to handle this error is by using Python exception handling ( try...except ).

    Exception handling is great when we are sure that some error could occur in a program , and it is mostly used for a large section of the code block. For trivial errors like KeyError , we can also use the dictionary get() method and Python in operators that can check whether a key already exists in a dictionary or not.

    With this, we can also handle this error in Python. Before discussing all the techniques, we can use to handle a KeyError in Python, let's first discuss the KeyEror itself.

    What is KeyError in Python?

    The KeyError is one of the standard Python exceptions. It is raised in a Python program when the programmer tries to access a dictionary item using a key that does not exist. Python dictionary stores all its elements in the form of keys and values, and we use the key to access the corresponding values. The keys are also data objects that are immutable and case-sensitive. Even if we pass the correct key data with the different cases or data types, we will still receive the KeyError.

    Example 1  ( Key Error due to nonexistent key name)

    rahul = {'Name': 'Rahul', 'Age':23, 'Gender':'Male'}
    
    # access rahul values with invalid key
    print('The Height of the Rahul is: ', rahul['Height'])

    Output

    Traceback (most recent call last):
      File "main.py", line 4, in 
        print('The Height of the Rahul is: ', rahul['Height'])
    KeyError: 'Height'

    In the above example, we are getting this error because we are trying to access the 'Height' value of the rahul dictionary, which does not exist.

    Example 2  ( Key Error due to sensitive casing)

    The key's names are also Python data objects, and they, like other objects' dictionary keys, are also case-sensitive. If we do not specify the exact key name while accessing the dictionary value, we encounter the KeyError.

    rahul = {'Name': 'Rahul', 'Age':23, 'Gender':'Male'}
    
    # access rahul values with invalid key
    print('The Age of the Rahul is: ', rahul['age'])

    Output

    Traceback (most recent call last):
      File "main.py", line 4, in 
        print('The Age of the Rahul is: ', rahul['age'])
    KeyError: 'age'

    In this example, we are getting the same KeyError, but the key name is different. When we defined the rahul dictionary, there we used them 'Age' as a key name,  but in line 4, we are trying to access that value using the 'age' name. If the cases of two keys are different, Python will treat them as different keys.

    Error Handling Solution

    Now let's discuss the different techniques we can use to handle this error in our Python program.

    1. Use the get() method to check if the key exists.
    2. Use the in operator to check if the key exists.
    3. Use the try...except block to handle the exception.

    1. Use the Dictionary get() method.

    Python dictionary provides the get() method, to access the value of a specific key. This method is an alternative to square brackets to access a dictionary element. The difference between using the square bracket and the get method is that the square bracket notation throw error if the key does not present in the dictionary, but the get() method does not throw an error. Instead, it returns None if the key is not valid.

    Syntax

    dictionary_name.get(key, default=None)
    
    

    The get method can accept two argument values.

    key : Is the key name which value we want to access?

    default : The value that needs to be returned if the key is not present in the dictionary. By default, its value is None.

    Example

    Now let's solve our Example 1 using the Python dictionary get method.

    rahul = {'Name': 'Rahul', 'Age':23, 'Gender':'Male'}
    
    # access rahul height
    print('The height of the Rahul is: ', rahul.get('Height', '!Not Found'))

    Output

    The height of the Rahul is: !Not Found

    It's always a good practice to provide a piece of valid information if the key is not present in the dictionary.

    2. Use Python in operator.

    Python provides an in operator that can check whether a key is present in a dictionary or Not. The in operator returns a boolean value, True or False, based on whether the key is in the dictionary or not. We can use the in operator and check for the condition of whether a key is present in a dictionary before calling it for a value.

    Syntax

    key in dictionary

    Example

    rahul = {'Name': 'Rahul', 'Age':23, 'Gender':'Male'}
    
    key = 'Height'
    
    # if key present in the dictionary
    if key in rahul:
        # access rahul height
        print('The height of the Rahul is: ', rahul[key])
    else:
        print(f'!{key} Not Found')

    Output

    !Height Not Found

    3. Use the try...except block to handle the exception.

    try..except is the Pythonic way to handle error in a Python program. In this, we define two blocks of code, one for the try block and another for the except block. In the try block, we write the code that may raise the error, and in the except block, we write the code that needs to be executed if the error is raised in the try block.

    Example

    rahul = {'Name': 'Rahul', 'Age':23, 'Gender':'Male'}
    
    key = 'Height'
    
    try:
        print("The Height of Rahul is: ", rahul['Height'])
    # if the KeyError raise in the try block
    except KeyError:
        print(f"!{key} Not Found")

    Output

    !Height Not Found

    Conclusion

    The KeyError is raised when we try to access a dictionary element with a key name that does not exist. If you are getting this KeyError in your program, you need to visit the error line code and check for the key you are passing in the square bracket. The easiest way to solve this error is using the get() method to access the key-value, instead of the square bracket notation.

    Although the square bracket notation is easy and quite similar to the indexing of a list, but when you deal with dictionaries, you should always consider using the get method.

    If you are still getting this error in your Python program, please share your code in the comment section. We will try to help you in debugging.

    People are also reading:

    Leave a Comment on this Post

    0 Comments