What Is a KeyError in Python Dictionaries, and How to Fix It?

Fix: KeyError in Python Dictionaries

Are you facing KeyError in Python dictionaries?

This article will discuss Python dictionaries, the reasons behind KeyError in Python dictionaries, and different solutions to fix KeyError in Python dictionaries, so keep reading. 📖

A Python dictionary is a data structure belonging to the collection class that stores data in key-value format. The key of a dictionary in Python can be an immutable and hashable object. In contrast, the value can be in any form, such as a tuple, list, list of things, another dictionary itself, and so on.

Let’s see an example of dictionaries in Python:

# create a dictionary

dic = {

 "f_name"  : "Zeeshan",

 "l_name"  : "Afridi",

 "age"     :  24,

 "height"  : 5.9,

 "Married" : False

}

print(dic)

 

Output

{'f_name': 'Zeeshan', 'l_name': 'Afridi', 'age': 24, 'height': 5.9, 'Married': False}


 

This is the general format of dictionaries in Python, and the data is in the key-value pairs. You can specifically print the values of keys see the below code example:

print(dic['f_name'])

 

Output

Zeeshan

 

We have asked Python to print values from the disc dictionary where the key is f_name, and in response, the Python compiler has published the values of the key, which is Zeeshan in this case.

 

 

What is a KeyError in Python Dictionary?

As we have seen in the above code examples, we can access the values of a dictionary using the defined keys. And if a non-existent key is given to a dictionary in Python, it throws a KeyError exception.

Let’s see an example of the error itself:

dic = {

 "f_name"  : "Zeeshan",

 "l_name"  : "Afridi",

 "age"     :  24,

 "height"  : 5.9,

 "Married" : False

}

print(dic["f_name"])

print(dic["l_name"])

print(dic["marks"])

 

Output

Zeeshan

Afridi

KeyError: 'marks'

 

The above code raised the KeyError: ‘marks’ exception when I tried to search for marks, but the values of f_name and l_name were printed successfully. And the logic behind this is that the first two keys are available in the dictionary, whereas marks aren’t defined in dic. Due to this reason, the Python compiler has raised the KeyError exception. 😊

Finally, we have dug into the problem and understood the reason behind the error. It’s time to give relevant solutions to fix KeyError in Python dictionaries.

 

 

How to Fix the KeyError with Python Dictionaries?

So far in this article, we have understood the reason behind the occurrence of the KeyError exception; now, let’s try to fix it! There could be numerous different methods to improve the KeyError when dealing with Python dictionaries, and the followings are a few of them:

  1. Use the get() method.
  2. Use if-else conditionals.
  3. Use try-catch exception handling.

Although these are not permanent solutions, it is still helpful in preventing your Python programs from crashing. Instead, it gives a warning on the use of an invalid key.

Let’s look at each one by one, along with examples:

 

Use the Get() Method

The get() method in Python returns a default value when a KeyError exception is raised. You can display any message as a default value against a KeyError exception.

Let’s look at a practical example of the get() method:

dic = {

 "f_name"  : "Zeeshan",

 "l_name"  : "Afridi",

 "age"     :  24,

 "height"  : 5.9,

 "Married" : False

}

# the default value

default = "The key does not exist\nPlease enter a valid key"

print(dic.get('marks', default))

 

Output

The key does not exist

Please enter a valid key

 

 

Use If-Else Conditionals

The use of conditional blocks to fix KeyError in Python is one of the most common but manual techniques to handle KeyError in Python. Let’s look at a practical example.

dic = {

 "f_name"  : "Zeeshan",

 "l_name"  : "Afridi",

 "age"     :  24,

 "height"  : 5.9,

 "Married" : False

}

key = input("Enter a key to get the value: ")

if key in dic:

 print(dic[key])

else:

 print("\nThe key does not exist\nPlease enter a valid key")

 

Output

Enter a key to get the value: marks

The key does not exist

Please enter a valid key

 

The above code will ask the user to enter and cross-check the key in the dictionary. If it is there, the corresponding value will be returned; otherwise, the else part will be executed. In this case, the else feature displays a default message to the user, as demonstrated in the above example.

 

 

Use Try-Catch Exception Handling

Try-Catch is one of the most common and useful exception-handling techniques used in Python to handle exceptions or potential commands that can lead to the program returning an error in its execution. And probably, it is the most suitable error and exceptional handling technique, so let’s dive deep into the practical part of it:

try:

 dic = {

 "f_name"  : "Zeeshan",

 "l_name"  : "Afridi",

 "age"     :  24,

 "height"  : 5.9,

 "Married" : False

 }

  key = input("Enter a key to get the value: ")

 dic[key]

except KeyError:

 print("\nOops! you have entered an invalid key\nPlease enter a valid key")

 

Output

Enter a key to get the value: marks

Oops! you have entered an invalid key

Please enter a valid key

 

In try-catch, we put the whole code in the try block, whereas the catch block is just used to identify the error and catch it before the program crashes. Once the exception is detected, the catch block is executed, which can be used accordingly, but we have just displayed a warning message.

 

 

Conclusion

To summarize this article on fixing the KeyError when using Python dictionaries, we have discussed what a KeyError is and how to fix it. In addition, we have discussed the 3 exception handling techniques and their corresponding code examples.

Let’s have a quick recap of the topics discussed in this article

  1. What is KeyError in Python dictionaries?
  2. How to fix KeyError in Pyhton dictionaries?
  3. Use the get() method to fix the KeyError with Python dictionaries.
  4. Use if-else to fix the KeyError with Python dictionaries.
  5. Use try-catch to fix the KeyError with Python dictionaries.

Learning moment 💡, name any scenario that causes KeyError in Python other than dictionary KeyError.

 

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts
Total
0
Share