Python Programming (136 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (26 Blogs)
  • Data Science (20 Blogs)
  • Mastering Python (84 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)

What is KeyError in Python? Dictionary and Handling Them

Last updated on Aug 14,2023 30.4K Views

Before we dive into KeyError in Python, it is important to know how a dictionary in python is set up. The following pointers will be discussed in this article:

To get in-depth knowledge of Python along with its various applications, you can enroll now for live Python course training with 24/7 support and lifetime access.

Dictionary in Python

The dictionary concept in Python is a random collection of values, which has stored data values like a map. It is unlike other data types that hold only a single value as an element. It holds the key: value pair.

KeyError in Python

The key value makes it more efficient. A colon separates a key and value pair and a ‘comma’ separates each key. This dictionary in python functions similar to a normal dictionary. The respective keys should be unique and of immutable data types such as strings, integers, and tuples, but the key-values can be iterated and is allowed to be of any type. There can be keys, which are strings that refer to numbers and vice versa.

Let us have a look at how a dictionary functions through the below-coded example.

# Creating an empty Dictionary 
Dict = {} 
print("Null dict: ") 

# Creating Dictionary with Integer Keys 
Dict = {1: 'Fun', 2: 'And', 3: 'Frolic'} 
print("nDictionary with the use of Integer Keys: ") 

# Creating Dictionary with Mixed keys 
Dict = {'Name': 'Arun', 1: [12, 23, 34, 45]} 
print("nDictionary with the use of Mixed Keys: ") 

# Creating a Dictionary with dict() method 
Dict = dict({1: 'German', 2: 'language', 3:'is fun'}) 
print("nDictionary with the use of dict(): ") 

# A Dictionary having each item as a Pair 
Dict = dict([(1, 'Hello'), (2, 'Bye')]) 
print("nDictionary with each item as a pair: ") 


KeyError in Python

Since we are clear on what a dictionary in python is and how it works. Now let us see what a key error is. KeyError in Python is raised when you attempt to access a key that is not in a dictionary.

The mapping logic is a data structure that maps one set of data to significant others. Hence, it is an error, which is raised when the mapping is accessed and not found. It is familiar to a lookup error where the semantic bug would be stated as the key you are looking for is not to be found in its memory. This can be better illustrated in the below code.

Here I am trying to access a key called “D” which is not present in the dictionary. Hence, the error is thrown as soon as it finds an exception. However, the remaining keys present in the dictionary, which are printed correctly, have the exact values corresponding to them. 



Handling Mechanism for a KeyError in Python

Anyone who encounters a KeyError can handle it in a responsible way. It is his skill to consider all possible inputs to a certain program and handle any precarious entries successfully.

Depending on your use case, some of these solutions might be better or may also not be the exact solution what you are looking for. Nevertheless, the ultimate goal is to stop unexpected key error exceptions from popping up.

If an error is brought from a dictionary in your own code, you can use .get() to extract either the value at the specified key or a default value. Let us have a look at a sample.

//List of fruits and their prices. 

fruits= {'Apple': 300, 'Papaya': 128, 'Kiwi': 233}
fruit= input('Get price for: ')
fruit1 = fruits.get(fruit)
if fruit1:
    print(f'{fruit} is {fruit1} rupees.')
    print(f"{fruit}'s cost is unknown.")


A Generic Solution to KeyError

The usual solution is that you can always use the try-except block to tackle such problems by raising the appropriate code and provide a backup solution. Check out the below code for more clarity.

 ages = {'Jophi': 12, 'Rao': 20, 'Irvin': 16} 
 person = input('Get age for: ')

    print(f'{person} is {ages[person]} years old.')
 except KeyError:
    print(f"{person}'s age is unknown.")

With this, we come to an end of this KeyError in Python article. I hope this article was informative in throwing light on Python’s KeyError exception and how it could be raised. Also, you may be aware now that in case the problem is a dictionary key lookup in your own code, then you can switch from accessing the key directly on the dictionary to using the .get() method with a default return value.

If the problem is not coming from your own code, then using the try-except block for better controlling your code’s flow.

To get in-depth knowledge of Python along with its various applications, you can enroll now for live Python course training with 24/7 support and lifetime access.

Got a question for us? Mention them in the comments section of “KeyError in Python” and we will get back to you.

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 27th July,2024

27th July

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 31st August,2024

31st August

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 28th September,2024

28th September

SAT&SUN (Weekend Batch)
View Details

Join the discussion

Browse Categories

webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is KeyError in Python? Dictionary and Handling Them