Python is the popular programming language. It is like English language. But any error may occurs while you use wrong syntax or exception. In this post you will know how to solve the python keyerror 0 exception in python.
Why Python KeyError 0 exception in Python Occurs ?
Lets know the main reason for getting this python keyerror. You are getting this error when you are trying to access the dictionary “0” key. As you cannot access the first key of the dictionary like this as it is not present inside the dictionary object.
You may encounter with the error when you will run the below lines of code.
my_dict = {1: ['a', 'b'], 2: ['c', 'd']}
print(my_dict[0])
Output
KeyError: 0
Solution of Python KeyError 0 exception in Python
There are many solutions for this error. And you will know most of them here.
Solution 1: Use the dict.get() function
The first solution is to use the dict.get() function to access the key of the dictionary.
You have to use the below lines of code.
my_dict = {1: ['a', 'b'], 2: ['c', 'd']}
print(my_dict.get(0))
print(my_dict.get(0, 'Your Default Value'))
The main benefit of using this dict.get() function is that if the key is not available in the dictionary then the default value otherwise it will return the accessed key. Thus this method never raise KeyError.
Solution 2: Add the value for the key before accessing
You can also set the value for the key 0 before accessing it. Thus it makes error proof. You will first initialize the my_dict[0] with an empty list and then add some elements to it using the append() function.
Use the below lines of code for that.
my_dict = {1: ['a', 'b'], 2: ['c', 'd']}
my_dict[0] = []
my_dict[0].append('e')
my_dict[0].append('f')
print(my_dict[0])
Solution 3 : Use try/except statement
The other solution to avoid this error is to us the try/except to handle the error. Here you will put the code in the try block and use the except KeyError to tell the user about the error and also initialize the dictionary with key 0 as an empty list.
Use the below code block.
my_dict = {1: ['a', 'b'], 2: ['c', 'd']}
try:
print(my_dict[0])
except KeyError:
print('key does not exist in dict')
my_dict[0] = []
Conclusion
You will get the python error 0 keyerror when you want to access the “0” key element but that key is not in the dictionary. The above solution will worked for you if you are getting this error.
Leave a Reply