PYTHON
Custom Dictionary with Default Values for Missing Keys
Create a dictionary-like structure in Python that returns a default value for missing keys, useful for flexible configuration or optional settings without KeyErrors.
class ConfigDict(dict):
"""A dictionary subclass that returns a specified default value
when a key is not found, instead of raising a KeyError.
"""
def __init__(self, default_value=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.default_value = default_value
def __missing__(self, key):
"""Called when a requested key is not found in the dictionary."""
if callable(self.default_value):
return self.default_value(key)
return self.default_value
# Example 1: Fixed default value
app_settings = ConfigDict('N/A', {'theme': 'dark', 'language': 'en'})
print(f"Theme: {app_settings['theme']}") # Output: dark
print(f"Language: {app_settings['language']}") # Output: en
print(f"Font size (missing): {app_settings['font_size']}") # Output: N/A
# Example 2: Dynamic default value using a callable (e.g., a lambda function)
user_preferences = ConfigDict(lambda key: f"Default for '{key}'", {'notify': True})
user_preferences['username'] = 'testuser'
print(f"Notify: {user_preferences['notify']}") # Output: True
print(f"Username: {user_preferences['username']}") # Output: testuser
print(f"Timezone (missing): {user_preferences['timezone']}") # Output: Default for 'timezone' (dynamic)
How it works: By subclassing `dict` and overriding its special `__missing__` method, you can define custom behavior when a non-existent key is accessed. Instead of raising a `KeyError`, this `ConfigDict` returns a pre-defined `default_value` or a dynamically generated value (if `default_value` is callable). This pattern is useful for managing configurations, optional settings, or API responses where you want graceful fallback for missing keys without explicit `dict.get()` calls or `try-except` blocks, offering more flexibility than `collections.defaultdict` for custom default value logic.