Support
Please support this website. Visit the Amazon using this affiliate link. There won't be any difference in your purchage, we will get some commission for every purchase you make.
Advertise with us
error python-tips   0   15064
Solving Python Error- KeyError: 'key_name'


As per Python 3 official documentation a key error is raised when a mapping (dictionary) key is not found in the set of existing keys.

This error is encountered when we are trying to get or delete the value of a key from a dictionary and that key doesn't exist in the dictionary.


rana@Brahma: ~$ python3
Python 3.5.2 (default, Jul 10 2019, 11:58:48) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = dict()
>>> a["key1"] = "value1"
>>> print(a["key2"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'key2'
>>> 



Accessing dictionary keys:

To access dictionary keys we use square brackets [ ].

>>> gender = dict()
>>> gender["m"] = "Male"
>>> gender["f"] = "Female"
>>> gender["m"]
'Male'
>>> 

However, the above method i.e using square brackets have one drawback. If the key doesn't exists we get KeyError.

>>> gender["k"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'k'
>>> 

Deleting not-existing key:

>>> del gender["h"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'h'
>>> 


To handle such cases, we can use one of the below techniques based on the scenario.

- Use method get()
We can get the value of a key from the dictionary using the get method. If a key-value pair does not exist for the given key in the dictionary, then None is returned, else the value of corresponding to that key is returned. This is the recommended way.

>>> gender.get("m")
'Male'
>>> gender.get("k")
>>> 
>>> print(gender.get("k") is None)
True
>>>


You can pass the second optional parameter in the get() call which is the value returned if the key doesn't exist in the dictionary. The default value of this second parameter is None.


- Check the existence of the key

We may check if any particular key exists in the dictionary or not and then based on that can take action. For example:

gender = dict()
gender["m"] = "Male"
gender["f"] = "Female"

if "k" in gender:
  print("Key k exists in gender")
else:
  print("Key k doesn't exists in gender")


- Use try-except

If you are not using or do not want to use get method to access the keys in the dictionary, use the try-except block.


gender = dict()
gender["m"] = "Male"
gender["f"] = "Female"

try:
  value = gender["k"]
except KeyError:
  print("Key error. Do something else")
except Exception:
  print("Some other error")


- Get all keys and iterate over the dictionary

We can use the keys() method to get the list of all keys in the dictionary and then iterate over that list and access the values in the dictionary.

gender = dict()
gender["m"] = "Male"
gender["f"] = "Female"

keys = gender.keys()

for key in keys:
  print(gender[key])


- Or you can directly iterate over the dictionary for key and value pairs using items() method.

gender = dict()
gender["m"] = "Male"
gender["f"] = "Female"

for item in gender.items():
  print(item[0], item[1])



Similarly for deleting a key-value from the dictionary, we can use the pop() method instead of del.

However, unlike get(), pop() method throws keyError if a key to be deleted doesn't exist and the second parameter is not passed.

So to avoid key error in case of key deletion, we must pass a default value to be returned, if the key is not found, as the second parameter to pop(),

>>> 
>>> gender.pop("m")
'Male'
>>> gender.keys()
dict_keys(['f'])
>>> gender.pop("k")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'k'
>>> gender.pop("k", None)
>>> 

 

error python-tips   0   15064
0 comments on 'Solving Python Error- Keyerror: 'Key_Name''
Login to comment


Related Articles:
Solving python error - ValueError: invalid literal for int() with base 10
This article explains what is ValueError: invalid literal for int() with base 10 and how to avoid it, python error - ValueError: invalid literal for int() with base 10, invalid literal for base 10 error, what is int() function, converting string to integer in python...
Solving python error - TypeError: 'NoneType' object is not iterable
In this article we are trying to understand what a NoneType object is and why we get python error - TypeError: 'NoneType' object is not iterable, Also we will try different ways to handle or avoid this error, python error NoneType object is not iterable, iterating over a None object safely in python...
Solving Python Error - UnboundLocalError: local variable 'x' referenced before assignment
UnboundLocalError: local variable 'x' referenced before assignment, solved UnboundLocalError in python, reason for UnboundLocalError in python, global vs nonlocal keyword in python, How to solve Python Error - UnboundLocalError: local variable 'x' referenced before assignment, nested scope in python, nonlocal vs global scope in python...
Python easter egg - import this and the joke
Zen of python, import this, the hidden easter egg with the joke, source code of Zen of python disobey itself...
DigitalOcean Referral Badge

© 2022-2023 Python Circle   Contact   Sponsor   Archive   Sitemap