PYTHON
Using frozenset as Dictionary Keys for Compound Immutable Keys
Explore how frozenset allows you to use immutable sets as dictionary keys, enabling complex, order-independent compound keys for caching or lookup tables in Python web apps.
# Scenario: Storing preferences for a pair of features, order-independent
feature_preferences = {}
# Define some features
feature_a = 'notifications'
feature_b = 'dark_mode'
feature_c = 'email_reports'
# Create frozensets for compound keys
# The order of elements in a frozenset does not matter for equality
key1 = frozenset([feature_a, feature_b])
key2 = frozenset([feature_b, feature_a]) # Same as key1
key3 = frozenset([feature_a, feature_c])
# Store data using frozenset keys
feature_preferences[key1] = {'display_order': 1, 'enabled': True}
feature_preferences[key3] = {'display_order': 2, 'enabled': False}
print(f"Preferences for {key1}: {feature_preferences.get(key1)}")
print(f"Preferences for {key2} (should be same as key1): {feature_preferences.get(key2)}")
print(f"Preferences for {frozenset(['dark_mode', 'notifications'])}: {feature_preferences.get(frozenset(['dark_mode', 'notifications']))}")
# Attempt to use a regular set (mutable) as a key - will raise TypeError
try:
my_set = {feature_a, feature_c}
feature_preferences[my_set] = "This will fail"
except TypeError as e:
print(f"Error using mutable set as key: {e}")
# Use case: Caching results based on multiple, order-independent input parameters
def get_combined_setting(feature_set: frozenset) -> dict:
# Imagine this fetches from a database or performs a heavy computation
print(f"Fetching setting for {feature_set}...")
return feature_preferences.get(feature_set, {'display_order': 99, 'enabled': False, 'default': True})
print(get_combined_setting(frozenset(['notifications', 'dark_mode'])))
print(get_combined_setting(frozenset(['notifications', 'email_reports'])))
print(get_combined_setting(frozenset(['unknown', 'features'])))
How it works: Dictionaries in Python require keys to be hashable (immutable). While regular set objects are mutable and thus not hashable, frozenset objects are immutable versions of sets and therefore are hashable. This allows them to be used as dictionary keys. This pattern is particularly useful when you need a compound key that represents a collection of items where the order of items does not matter, such as feature combinations, permission sets, or cached results based on multiple, order-independent parameters.