PYTHON
Safely Access Nested Dictionary Values in Python
Learn to safely access deeply nested dictionary values in Python, preventing KeyError exceptions when keys might be missing. Essential for robust data parsing.
def get_nested_value(data, keys, default=None):
"""
Safely retrieves a value from a nested dictionary structure.
Args:
data (dict): The dictionary to search within.
keys (list): A list of keys representing the path to the desired value.
default: The default value to return if any key in the path is not found.
Returns:
The value found at the specified path, or the default value if not found.
"""
current_data = data
for key in keys:
if isinstance(current_data, dict) and key in current_data:
current_data = current_data[key]
else:
return default
return current_data
# Example Usage:
config = {
"user": {
"profile": {
"name": "Alice",
"email": "[email protected]"
},
"settings": {
"theme": "dark"
}
},
"app": {
"version": "1.0"
}
}
# Valid path
username = get_nested_value(config, ["user", "profile", "name"])
print(f"Username: {username}")
# Invalid path - 'address' does not exist
user_city = get_nested_value(config, ["user", "profile", "address", "city"], "N/A")
print(f"User City: {user_city}")
# Path to a non-dictionary intermediate value
app_feature = get_nested_value(config, ["app", "version", "feature"], "Unknown")
print(f"App Feature: {app_feature}")
# Top-level key missing
admin_email = get_nested_value(config, ["admin", "contact"], "[email protected]")
print(f"Admin Email: {admin_email}")
How it works: This snippet provides a utility function `get_nested_value` to safely retrieve data from deeply nested dictionaries. It iterates through a list of keys, checking at each step if the current key exists and if the data is still a dictionary. If any key is missing or an intermediate value is not a dictionary, it gracefully returns a specified default value instead of raising a `KeyError`, making your code more robust when handling unpredictable data structures like JSON API responses.