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)
SEE MORE

What is KeyError in Python? Dictionary and Handling Them

Last updated on Aug 14,2023 30.1K 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: ") 
print(Dict) 

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

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

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

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

 

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. 

// 
ages={'A':30,'B':28,'C':33}
print(ages['A'])
print(ages['B'])
print(ages['C'])
print(ages['D'])
//

 

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. 

while(1):
fruits= {'Apple': 300, 'Papaya': 128, 'Kiwi': 233}
fruit= input('Get price for: ')
fruit1 = fruits.get(fruit)
if fruit1:
    print(f'{fruit} is {fruit1} rupees.')
else:
    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.

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

 try:
    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 20th April,2024

20th April

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

Class Starts on 18th May,2024

18th May

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

Class Starts on 22nd June,2024

22nd June

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
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

edureka.co