![]() |
VOOZH | about |
We are given a dictionary and our task is to retrieve the value associated with a given key. However, if the key is not present in the dictionary we need to handle this gracefully to avoid errors. For example, consider the dictionary : d = {'name': 'Alice', 'age': 25, 'city': 'New York'} if we try to access d['age'] then we get 25. But if we attempt to access d['country'], it results in a KeyError.
The simplest way to access a value in a dictionary is by using bracket notation ([]) however if the key is not present, it raises a KeyError.
25
Explanation: d['age'] returns 25 because 'age' exists in the dictionary and d['country'] raises a KeyError since 'country' is not a key in d.
get() method allows retrieving a value from a dictionary while providing a default value if the key is missing, this prevents KeyError and makes the code more robust.
25 Not Found
Explanation: d.get('age') returns 25 since the key exists and d.get('country', 'Not Found') returns 'Not Found' instead of raising an error.
setdefault() method retrieves the value of a key if it exists otherwise inserts the key with a specified default value and returns that default.
25
USA
{'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}
Explanation: d.setdefault('age') returns 25 since the key exists and d.setdefault('country', 'USA') inserts 'country': 'USA' into the dictionary and returns 'USA'.
defaultdict class from the collections module is an advanced dictionary type that provides a default value when a missing key is accessed, this prevents KeyError and is useful when handling multiple missing keys efficiently.
Country: India
Explanation: