PYTHON
Utilize `frozenset` for Immutable Sets and Dictionary Keys
Learn about Python's `frozenset` to create immutable sets, enabling them to be used as dictionary keys or elements within other sets, which is not possible with regular mutable sets.
# Regular set is mutable
s = {1, 2, 3}
# s_mutable = {1,2}
# my_dict = {s_mutable: "value"} # This would raise TypeError: unhashable type: 'set'
# Frozenset is immutable and hashable
fs1 = frozenset([1, 2, 3])
fs2 = frozenset([3, 4, 5])
print(f"Frozenset 1: {fs1}")
# Frozensets can be used as dictionary keys
config_map = {
frozenset(['admin', 'editor']): 'High Access',
frozenset(['viewer']): 'Read Only'
}
print(f"
Access level for {{'admin', 'editor'}}: {config_map[frozenset(['admin', 'editor'])]}")
# Frozensets can be elements of other sets
set_of_frozensets = {frozenset([1, 2]), frozenset([3, 4])}
print(f"Set containing frozensets: {set_of_frozensets}")
# Operations are similar to regular sets
intersection_fs = fs1.intersection(fs2)
print(f"Intersection of frozensets: {intersection_fs}")
# Attempting to modify a frozenset raises an AttributeError
try:
fs1.add(4)
except AttributeError as e:
print(f"
Error trying to add to frozenset: {e}")
How it works: While standard Python `set` objects are mutable, `frozenset` provides an immutable version of a set. This immutability is crucial because it makes `frozenset` objects hashable, allowing them to be used as keys in dictionaries or as elements within other sets. This is particularly useful for scenarios where you need to map or categorize based on a collection of unique items (e.g., user roles for permissions) or when you need a hashable, unchanging representation of a set for caching or lookup purposes.