error python-tips   0   677
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   677

Related Articles:
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...
Difference between list, set and tuples in Python and more such comparisons
Difference between tuples and lists, raw_input and input, shallow and deep copy, args and kwargs and other different terms explained in python...
5 common mistakes made by beginner python programmers
Most common mistakes made by beginner python programmers, Things to avoid by python programmers, Most common pitfalls/ gotchas in python, Bitten by python scenarios, tips for beginner python programmers, python beginner programmers should avoud these mistakes...
Print statement in Python vs other programming languages
print statement in Python vs Other programming languages, comparing python simplicity with other programming languages, how to print a string in python, print statement in python, comparing python with other languages, python vs java, python vs c++...

SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.


Recent Posts:






© 2017-2019 Python Circle   Contact Us   Advertise with Us