PYTHON
Using Frozenset as Immutable Dictionary Keys
Explore frozenset in Python to create immutable set-like objects that can serve as dictionary keys, perfect for caching, memoization, or representing unique combinations in web applications.
# Define a function to process an order
def calculate_price(items):
# Simulate a complex calculation
base_price = sum(len(item) * 10 for item in items)
if 'discount' in items:
base_price *= 0.9
return base_price
# Cache for memoization using frozenset as keys
price_cache = {}
def get_order_price(items_list):
# Convert list of items to a frozenset for a canonical, hashable key
# Order of items in the list won't affect the frozenset
key = frozenset(items_list)
if key in price_cache:
print(f"Fetching price for {items_list} from cache.")
return price_cache[key]
else:
print(f"Calculating price for {items_list} and caching.")
price = calculate_price(items_list)
price_cache[key] = price
return price
# Example Usage
order1 = ['apple', 'banana', 'orange']
order2 = ['banana', 'apple', 'orange'] # Same items, different order
order3 = ['apple', 'banana', 'discount']
order4 = ['apple', 'grape']
print(f"Price for order1: {get_order_price(order1)}")
print(f"Price for order2: {get_order_price(order2)}") # Should hit cache
print(f"Price for order3: {get_order_price(order3)}")
print(f"Price for order4: {get_order_price(order4)}")
print(f"Price for order1 again: {get_order_price(order1)}") # Should hit cache
print(f"
Current price cache: {price_cache}")
How it works: frozenset is an immutable version of Python's built-in set. Because it's immutable, frozenset objects are hashable and can be used as keys in dictionaries. This snippet demonstrates its utility for memoization, where complex function results are cached based on their inputs. By converting a list of items (whose order might vary but content is the same) into a frozenset, a canonical and unique key is created, allowing the cache to effectively identify and retrieve previously computed results, preventing redundant calculations and improving performance in web services.