. Advertisement .
..3..
. Advertisement .
..4..
Are you a beginner working on a python program? Getting KeyError: 0 exception in Python? It’s one of the errors you may encounter, which is not a code error. It means when you get this error warning, it doesn’t mean you end up coding incorrectly.
Let’s take a look at what is KeyError: 0 exception in Python
What is KeyError: 0 exception?
It is a runtime error that occurs when a key is not found in a dictionary. The dictionary is a term that signifies an unsorted collection of objects that works to handle the key’s data type. Being data structures of Python version, it is also known as associative arrays.
In short, this error occurs when you try to access any key from the dictionary that doesn’t exist.
How to Fix KeyError: 0 exception in Python?
There are different methods to fix KeyError in Python. Let’s figure out the methods with example
Using Get Method
To return the value of the key, this method works with the dictionary. Get method returns the default when the key prompted can’t be located. In this case, there is no default value outputted, so the Get method ensures key error doesn’t occur
studentAge = {'cristian': 19, 'sergio': 21, 'david': 20, 'mohamed': 18 }
student = input("Get student age for: ")
studentAge = studentAge.get(student)
if studentAge:
print(f'{student} is {studentAge} years old.')
else:
print(f"{student}'s age is unknown.")
Output
# input is 'david'
Get student age for: david
david is 20 years old.
# input is 'wayne'
Get student age for: wayne
wayne's age is unknown.
We will get a KeyError exception if we don’t use the get()
method. Key is assigned as ‘employeeage’ in the dictionary. with the help of the get method, a program is prompted to fetch age directly itself instead of the key.
Using In Operator Method
When using this method, it is indispensable to understand the keys and values. When it comes to checking a particular range of values in a dictionary, In operator method is quite efficient. It only returns the values existing without key error.
a = {1: 9, 4: 6, 5: 8, 7: 12, 9: 25}
for i in range(1, 8):
if i in a:
print(a[i])
Output
9
6
8
12
You can get the output as 9,6,8,12. Many other keys between 1 and 8 are not present.
Using Try-Except Block Method
This one is the simplest method to try. In the try-except
block method, the executions occur in the loop. It doesn’t let the program stop during execution.
a = {1: 9, 4: 6, 5: 8, 7: 12, 9: 25}
for i in range(1, 10):
try:
print(a[i])
except KeyError:
var = 0
Output
9
6
8
12
25
No KeyError returned as this method didn’t let the program stop the execution.
Using Exception Handling Method
With this method, if a key value is 0 in the dictionary, the output will not be 0.
studentList = {'Name': 'Diego', 'Code': 6817}
try:
studentCode = studentList['Code']
print(studentCode)
emp_dep = studentList['Department']
print(emp_dep)
except KeyError as e:
print('Code Not Found in student details:', e)
Output
6817
Code Not Found in student details: 'Department'
Using try-Except-Else Method
It deals with the exception, and works in three patterns; try, except, and else.
fruits = {'Apple': 25, 'Coconut': 18, 'Pear': 15, 'Mango': 42}
item = input('Get fruits:')
try:
print(f'The {item} is {fruits[item]}')
except KeyError:
print(f'The {item} is not have')
else:
print(f'There is no error in the statement')
Output:
# case 1
Get fruits:lemon
The lemon is not have
# case 2
Get fruits:Apple
The Apple is 25
There is no error in the statement
In the code, the fridge has no assigned key, but a part of the dictionary. This method prevented KeyError.
Conclusion
Here, we have discussed all possible ways to get rid of KeyError: 0 exception in Python. I hope you will get through this exception!
Leave a comment