PYTHON
Using `frozenset` as Dictionary Keys
Discover how `frozenset` allows you to use immutable sets as dictionary keys, enabling caching or lookup of unique combinations of elements in web applications.
# Representing user roles or permissions as frozensets
admin_roles = frozenset(["read", "write", "delete"])
editor_roles = frozenset(["read", "write"])
viewer_roles = frozenset(["read"])
# A dictionary mapping permission sets to specific access levels or functions
access_levels = {
admin_roles: "Full Admin Access",
editor_roles: "Content Editor Access",
viewer_roles: "Read-Only Access",
frozenset(["read", "upload"]): "Uploader Access" # Define on the fly
}
user_permission_set_1 = frozenset(["read", "write"])
user_permission_set_2 = frozenset(["read", "delete", "write"]) # Order doesn't matter for frozenset equality
print(f"User 1 access: {access_levels.get(user_permission_set_1, 'No Access')}")
print(f"User 2 access: {access_levels.get(user_permission_set_2, 'No Access')}")
print(f"Viewer access: {access_levels.get(viewer_roles, 'No Access')}")
# Attempting to use a mutable set as a key would raise an error
try:
mutable_set = {"item1", "item2"}
# This line would cause an error: TypeError: unhashable type: 'set'
# some_dict = {mutable_set: "value"}
except TypeError as e:
print(f"
Attempted to use mutable set as key (expected error): {e}")
# Example output:
# User 1 access: Content Editor Access
# User 2 access: Full Admin Access
# Viewer access: Read-Only Access
#
# Attempted to use mutable set as key (expected error): unhashable type: 'set'
How it works: Unlike regular `set`s, `frozenset`s are immutable and therefore hashable, meaning they can be used as keys in dictionaries or elements in other sets. This is particularly useful in web development for scenarios where you need to map unique combinations of attributes, roles, or permissions to specific values or behaviors. For instance, caching results based on a set of parameters or defining access levels for different permission sets becomes straightforward and efficient.