Python | Dictionary KeyError Handling

Python Dictionary is an unordered collection of key:value pairs. These can be really useful for dealing with kind of Structured Data inside a Program. Like if you have want to simulate data of Laptop name and its manufacturing year then Python Dictionary is way to go. For example – {“Mac”: 2018, “HP”: 2014, “Lenovo”: 2013} is a Dictionary. In order to retrive/update dictionaries in Python. There does exist many methods/functions, if your not aware of these then see Dictionary Methods in Python Programming Language article.

Specifically for Methods which are used for retrieving keys/values from dictionary may raise errors like KeyError. A KeyError is raised by Python when a key doesn’t exist inside dictionary but your using some method to access that key.

Dictionary KeyError Exception in Python

Exception raised by Python, when it doesn’t find key inside dictionary which its looking for. Its kind of same as if you go to your local store for buying milk and you don’t find it in store then you go to customer service person in store to raise concern about Why no milk in store?
Below is a code example showing KeyError Exception for Dictionary Obejct in Python

>>> dict1 = {1: "Computer", 2: "Science", 3:"Hub"}
>>> dict1
{1: 'Computer', 2: 'Science', 3: 'Hub'}
>>> dict1[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 4

3 Ways to handle KeyError Exception for Dictionary in Python

Now as your aware of what’s KeyError and when its raised by Python. Then next question would be How to avoid this errors in code? You can do this error handling using three ways.

  • if…….else loop for KeyError Handling
  • try…….except for KeyError Handling
  • get() method for KeyError Handling

Handling Dictionary KeyError using if…else loop

Before accessing the key inside a Dictionary, using if… else loop you can check whether key exists inside dictionary or not even before accessing key. For this first you need to access keys of dictionary by using dict_keys() Method.
Below is a code example showing How you can use if…..else loop for handling Dictionary KeyError in Python.

# Creating a Python Dictionary
dict1 = {1: "Hello", 2: "How", 3:"Are", 4:"You"}

# Accessing some key from dict1
keyname = 5                       # Setup whatever you want to access from dictionary
if keyname in dict1_keys():
	print(keyname + " is in dictionary")
else:
	print(keyname + " is not in dictionary")

Handling Dictionary KeyError using try…..except code block

Python’s Error catch code block try…except can also be used for checking whether some key is there in dictionary or not.
Below is a code example showing How to use try..except for handling Dictionary KeyError in Python.

# Creating a Python Dictionary
dict1 = {1:"USA", 2:"India", 3:"Uk"}

# Handling KeyError
keyname = 5

try:
	print(dict1[keyname])
except KeyError:
	print(str(keyname) + " is not in dictionary")

Just note here that common practice for except KeyError: in Python is to print out 0 number. So most commonly Python Developers code this as folllowing.

# Creating a Python Dictionary
dict1 = {1:"USA", 2:"India", 3:"Uk"}

# Handling KeyError
keyname = 5

try:
	print(dict1[keyname])
except KeyError:
	print(0)

Handling KeyError using get() method

Python’s get() method can also be used for retrieving value corresponding to some key, but one advantage with this method is that you can explicitly specify some default value to return if key is not in Dictionary.

Syntax : get(keyname, optional default value)

Blow is a code example showing How to use get() method for handling Dictionary KeyErrors?

dict1 = {1:"Apple", 2:"Banana", 3:"Grapes"}
dict1.get(1, 0)              # Returns Apple
dict1.get(4, 0)              # Returns 0 default value meaning key 4 is not in dictionary

Final thoughts

For handling Dictionary KeyError, you can use any of three methods which I’ve mentioned above. Just keep in mind that if your working as part of a Python Developers Team, then use 0 for try…except error handling block. This would keep things simple and your colleagues would be able to understand code quickly.

You may also find following articles about Python Programming Language useful.

Happy Coding 🥳

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

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

Recent Posts