PYTHON
Safely Accessing Nested Dictionary Values with Default Fallbacks
Learn to reliably access values in deeply nested dictionaries using `dict.get()` to prevent `KeyError` and provide default values, ideal for JSON parsing.
def get_nested_value(data, path, default=None):
""" Safely retrieves a value from a nested dictionary given a path (list of keys). """
current = data
for key in path:
if isinstance(current, dict):
current = current.get(key, default) # Use .get() to prevent KeyError
if current == default and key != path[-1]: # If an intermediate key is missing, return default immediately unless it's the last key and default is a valid value for it.
return default
else:
# If at any point current is not a dict, further traversal is impossible
return default
return current
# Example usage with typical API response structure:
api_response = {
"status": "success",
"data": {
"user": {
"id": 123,
"name": "Alice",
"details": {
"email": "[email protected]",
"phone": "123-456-7890"
}
},
"settings": {
"notifications": True
}
}
}
# Accessing existing value
email = get_nested_value(api_response, ["data", "user", "details", "email"], "N/A")
print(f"User email: {email}") # Output: User email: [email protected]
# Accessing a non-existent value with default
country = get_nested_value(api_response, ["data", "user", "address", "country"], "Unknown")
print(f"User country: {country}") # Output: User country: Unknown
# Accessing a value where an intermediate key is missing
admin_level = get_nested_value(api_response, ["data", "user", "permissions", "admin_level"], 0)
print(f"User admin level: {admin_level}") # Output: User admin level: 0
# Accessing a top-level key that might be missing
error_message = get_nested_value(api_response, ["error", "message"], None)
print(f"Error message: {error_message}") # Output: Error message: None
# Accessing a path where an intermediate value is not a dictionary
invalid_path = get_nested_value(api_response, ["data", "user", "id", "type"], "Not Found")
print(f"Invalid path access: {invalid_path}") # Output: Invalid path access: Not Found
How it works: This snippet provides a robust function for safely accessing values deep within nested dictionaries, a common challenge when parsing dynamic data like JSON API responses. It takes the dictionary, a list representing the key path, and an optional default value. It iterates through the path, using `dict.get()` at each step to gracefully handle missing keys by returning the specified default value instead of raising a `KeyError`. This prevents crashes and makes code more resilient to changes in data structure.