Last Updated : 04 Feb, 2025
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.
Using Bracket Notation ([])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.
Python
d = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Accessing an existing key
print(d['age'])
# Accessing a non-existent key (Raises KeyError)
#print(d['country'])
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.
Using get() Methodget() 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.
Python
d = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Accessing an existing key
print(d.get('age'))
# Accessing a non-existent key with a default value
print(d.get('country', '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.
Using setdefault() Methodsetdefault() method retrieves the value of a key if it exists otherwise inserts the key with a specified default value and returns that default.
Python
d = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Accessing an existing key
print(d.setdefault('age'))
# Accessing a non-existent key and setting a default value
print(d.setdefault('country', 'USA'))
print(d)
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'.
Using defaultdict from collectionsdefaultdict 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.
Python
from collections import defaultdict
# Creating a defaultdict with a default value of 'Unknown'
d = defaultdict(lambda: 'Unknown', {'name': 'geeks', 'age': 21, 'place': 'India'})
# Accessing value using bracket notation
val = d['place']
print("Country:", val)
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4