The dict.get() method in Python returns the value associated with a given key. If the key is not present, it returns None by default or a specified default value if provided. It allows safe access to dictionary keys without raising a KeyError.
Example: In this example, here a value is retrieve from a dictionary using get().
d = {'coding': 'good', 'thinking': 'better'}
print(d.get('coding'))
Output
good
Explanation: d.get('coding') returns the value linked to 'coding'. Since the key exists, its value is returned.
Syntax
dict_name.get(key, default_value)
Parameters:
- key: The key whose value needs to be retrieved.
- default_value (optional): Value returned if the key is not found. Default is None.
Return Value:
- Returns the value of the specified key.
- Returns default_value (or None) if the key does not exist.
Examples
Example 1: In this example, a default value is provided that is returned when the key is missing.
d = {1: '001', 2: '010', 3: '011'}
print(d.get(4, "Not found"))
Output
Not found
Explanation: d.get(4, "Not found") checks for key 4. Since 4 is not present, "Not found" is returned.
Example 2: In this example, we use chained get() to safely access nested dictionary values.
d = {'Gfg': {'is': 'best'}}
res = d.get('Gfg', {}).get('is')
print(res)
Output
best
Explanation:
- d.get('Gfg', {}) returns nested dictionary.
- .get('is') retrieves value safely.
- If 'Gfg' was missing, {} prevents KeyError.
Example 3: Here, get() is compared with direct key access when a key is missing.
d = {'a': 10}
print(d.get('b'))
print(d.get('b', 0))
Output
None 0
Explanation:
- d.get('b') returns None because key is missing.
- d.get('b', 0) returns 0 as default value.
- No KeyError is raised.