Python dictionary key error

In this Python tutorial, we will study How to solve Python dictionary key errors using some examples in Python. Moreover, we will also cover why Python KeyError Occurs when the Key Exists and how to avoid KeyErrors.

What is a KeyError in Python Dictionary?

A KeyError in Python is raised when a dictionary is accessed with a key that does not exist in that dictionary. Consider the following example:

dictionary = {"name": "John", "age": 25}

In the above code snippet, trying to print dictionary["profession"] results in a KeyError because the key “profession” does not exist in the dictionary.

Python dictionary key error occur

Why Does a KeyError Occur When the Key Exists?

Despite the key existing in the dictionary, a KeyError can still occur due to various reasons:

  1. Case Sensitivity: Python is a case-sensitive language. Therefore, ‘Key’ and ‘key’ are different. If your dictionary contains a key “Key” and you attempt to access it with “key”, a KeyError will be thrown.
  2. Leading or Trailing Whitespaces: If your dictionary key includes leading or trailing spaces, for example, ‘ key‘, and you try to access it without including those spaces, it will result in a KeyError.
  3. Incorrect Data Type: The data type of the key also matters. For instance, the integer 1 is not the same as the string ‘1’. If your dictionary key is an integer and you try to access it using a string (or vice versa), it will raise a KeyError.

How to Avoid KeyErrors in Python Dictionary

Check If the Key Exists

You can check if a key exists in the dictionary before accessing it:

state_info = {
    "State": "California",
    "Capital": "Sacramento",
    "Region": "West"

key_to_check = "State"

if key_to_check in state_info:
    print(f"Key '{key_to_check}' does not exist in the dictionary.")

In this code, we first check if key_to_check exists in the Python dictionary state_info using the in operator. If it does, we print its associated value. If it doesn’t, we print a message indicating that the key does not exist.

READ:  How to Get the Index of the Minimum Element of a List in Python [6 Methods]


Python dictionary key error

Use the get() Method

Python provides a get() method that returns the value for a key if it exists in the dictionary. If the key doesn’t exist, it returns a default value:

car_info = {
    "Make": "Ford",
    "Model": "Mustang",
    "Year": 2018

key_to_check = "Engine"

print(car_info.get(key_to_check, "Key does not exist in the dictionary."))

Here, we try to access the value for the key “Engine” using the get() method. Since “Engine” does not exist in car_info, the get() method returns the provided default value, “Key does not exist in the dictionary.”


Python dictionary key error example

Use dict.setdefault()

The setdefault() method returns the value of a key (if the key is in dictionary). If not, it inserts the key with a value to the Python dictionary.

book_info = {
    "Title": "To Kill a Mockingbird",
    "Author": "Harper Lee",
    "Publication Year": 1960

key_to_check = "Pages"

value = book_info.setdefault(key_to_check, "Unknown")

Since “Pages” does not exist in book_info, setdefault() inserts “Pages” with a value of “Unknown” into the dictionary and then returns “Unknown”. The book_info Python dictionary now includes the new key-value pair “Pages”:”Unknown”.


How to solve Python dictionary key errors

Read Python Dictionary KeyError: None

Handle KeyError Using Exception Handling

In Python, you can use a try-except block to catch exceptions and handle errors. This is also applicable for KeyError.

team_info = {
    "Team Name": "Los Angeles Lakers",
    "Founded": 1947,
    "Championships": 17

key_to_check = "League"

except KeyError:
    print(f"Key '{key_to_check}' does not exist in the dictionary.")

In this case, we attempt to print the value of “League” from team_info. Because the key “League” doesn’t exist, a KeyError would be raised. But, due to the try-except block, Python executes the except block, printing a message that the key does not exist.

READ:  How to convert string to boolean in Python? [6 Methods]


How to solve Python dictionary key errors example


While a KeyError generally indicates that the specified key does not exist in the dictionary, it can sometimes be raised even if the key seemingly exists due to reasons such as case sensitivity, leading or trailing spaces, and incorrect data type.

Several methods, such as using conditional checks, get(), setdefault(), and exception handling, can be employed to prevent this error. Understanding these pitfalls and solutions can help write more robust and error-free Python code.

You may also like to check the following python tutorials.