Data Science and Machine Learning Internship ...
- 22k Enrolled Learners
- Weekend/Weekday
- Live Class
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.
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.
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)
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']) //
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.")
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.
Course Name | Date | Details |
---|---|---|
Python Programming Certification Course | Class Starts on 30th November,2024 30th November SAT&SUN (Weekend Batch) | View Details |
Python Programming Certification Course | Class Starts on 28th December,2024 28th December SAT&SUN (Weekend Batch) | View Details |
edureka.co