. Advertisement .
..3..
. Advertisement .
..4..
Python has an infinite number of programs that programmers have been trying to design web applications. It is a vast language with a lot of benefits, but you need to know that there can be many errors that need to be fixed. Learners make more errors as they are in the beginning phase of learning the language. Get the KeyError: 1 exception in Python? Don’t worry as we are going to highlight the issue and how to tackle it.
The KeyError: 1 exception in Python occurs when trying to access a ‘1’ key in a dictionary, which has no key. Check out how to fix KeyError: 1 exception error
How to Fix KeyError: 1 exception in Python
The error arises when you are trying to work in a dictionary with a ‘1’ key, and there is no sign of that key in the dictionary. Here is an example
Code:
dict1 = {2: ['Pigeon', 'Sparrow'], 3: ['Penguin', 'Swan']}
print(dict1[1])
Error message:
Traceback (most recent call last):
File "code.py", line 10, in <module>
print(dict1[1])
KeyError: 1
As we have discussed, when trying to access a key ‘1’ in a dictionary that doesn’t contain the key.
Set Value for the key
To solve the KeyError, you need to set the value for the key before you are trying to access it.
dict2 = {2: ['Pigeon', 'Sparrow'], 3: ['Penguin', 'Swan']}
dict2[1] = []
dict2[1].append('Falcon')
dict2[1].append('Flamingo')
print(dict2[1])
Output
['Falcon', 'Flamingo']
The ‘1’ key has been initialized to an empty list in this example.
Use dict.items() Method
In the case, you want to iterate over a dictionary, the dict.item()
method is used. It returns a dictionary’s items with a new view ((key, value) pairs). Have a look at the example
dict3 = {1: ['Falcon', 'Flamingo'], 2: ['Pigeon', 'Sparrow'], 3: ['Penguin', 'Swan']}
for key, value in dict3.items():
print(key, value)
Output
1 ['Falcon', 'Flamingo']
2 ['Pigeon', 'Sparrow']
3 ['Penguin', 'Swan']
Use dict.get() Method
Another way to solve KeyError: 1 exception, the dic.get()
is a method that can be used. If the key is in the dictionary, this method returns the value for the specified key, or else returns a default value.
Code:
dict4 = {2: ['Pigeon', 'Sparrow'], 3: ['Penguin', 'Swan']}
print(dict4.get(1)) # None
print(dict4.get(1, 'empty value')) # 'empty value'
Output:
None
empty value
if you don’t provide the value for the ‘default’ parameter, it returns ‘None’ by default. You will never get a KeyError with this method.
Use the Try/Except Method
Try and except method works to avoid the KeyError. The ‘except’ clause takes care of the error as here you can initialize key ‘1’ if required. See the example
Code:
dict5 = {2: ['Pigeon', 'Sparrow'], 3: ['Penguin', 'Swan']}
try:
print(dict5[1])
except KeyError:
print('The key does not exist in dict')
dict5[1] = []
Output:
The key does not exist in dict
In order to avoid the error, you can use this class. This class takes an argument ‘default_factory
’ that calls it to assign a default value to the specified key. It inserts the key value in the dictionary. Here is an example
Code:
from collections import defaultdict
dict6 = defaultdict(list)
dict6[1].append('Falcon')
dict6[1].append('Flamingo')
print(dict6)
Output:
defaultdict(<class 'list'>, {1: ['Falcon', 'Flamingo']})
Conclusion
We highlight all the ways to fix KeyError: 1 exception in Python. With this, I wish you happy coding!
Try the above ways to get your code working!
Leave a comment