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'
>>>
To access dictionary keys we use square brackets [ ]
.
>>> gender = dict() >>> gender["m"] = "Male" >>> gender["f"] = "Female" >>> gender["m"] 'Male' >>>
>>> gender["k"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'k' >>>
>>> del gender["h"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'h' >>>
get()
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) >>>