![]() |
VOOZH | about |
In Python, dictionaries are key-value containers that provide fast access to data with a time complexity of O(1). However, in many applications, the user may not know all the keys present in a dictionary. Accessing a missing key directly results in a KeyError.
For Example:
Output
KeyError: 'c'
Notice that key = 'c' doesn't exist in the dictionary and that's why accessing it is giving KeyError.
Below are different methods of handling this in Python:
defaultdict from the collections module is highly efficient and avoids repeatedly writing checks. It allows you to set a default value for missing keys at the time of dictionary creation.
1 Key Not found
Explanation:
get() method allows you to retrieve a value if the key exists, or return a default value otherwise.
0091 Not Found
Explanation:
setdefault() method works like get(), but if the key is missing, it creates the key with a default value.
0091 Not Present
Explanation:
You can handle missing keys by catching the KeyError exception
0091 Not Found
Explanation:
Key not found
Explanation: