PYTHON
Safely Access Nested Dictionary Values with a Custom Function
Prevent KeyError exceptions when parsing complex JSON or dictionary structures by implementing a robust function for safe, deep access to nested values in Python.
def get_nested_value(data: dict, keys: list, default=None):
""" Safely retrieves a value from a nested dictionary structure. """
current_level = data
for key in keys:
if isinstance(current_level, dict) and key in current_level:
current_level = current_level[key]
else:
return default
return current_level
# Example Usage:
api_response = {
"user": {
"profile": {
"name": "Alice",
"email": "[email protected]"
},
"settings": {
"theme": "dark"
}
},
"status": "active"
}
# Access existing value
name = get_nested_value(api_response, ['user', 'profile', 'name'])
print(f"User Name: {name}") # Output: User Name: Alice
# Access non-existing path with default
country = get_nested_value(api_response, ['user', 'profile', 'address', 'country'], 'Unknown')
print(f"User Country: {country}") # Output: User Country: Unknown
# Access non-existing top-level key
product_id = get_nested_value(api_response, ['product', 'id'])
print(f"Product ID: {product_id}") # Output: Product ID: None
How it works: This function provides a safe way to access deeply nested values within a dictionary, common when parsing JSON responses from APIs. Instead of direct indexing (e.g., `data['user']['profile']['name']`) which can raise a `KeyError` if any intermediate key is missing, this function iterates through the list of keys. It checks if each key exists and if the current level is indeed a dictionary before proceeding. If any key is missing at any level, it gracefully returns a specified `default` value (which is `None` by default), preventing application crashes.