PYTHON

Use Immutable Sets (frozenset) in Python for Dictionary Keys and Hashable Collections

Explore frozenset in Python to create immutable, hashable sets. Perfect for use as dictionary keys, set elements, or when you need a constant collection for better data integrity.

# Create a frozenset
fs1 = frozenset([1, 2, 3, 2])
fs2 = frozenset({3, 1, 2})
print(f"frozenset 1: {fs1}")
print(f"frozenset 2: {fs2}")

# Frozensets are immutable - cannot add or remove elements
try:
    # fs1.add(4) # This will raise an AttributeError
    print("Attempting to add to frozenset will fail.")
except AttributeError as e:
    print(f"Error: {e}")

# Frozensets are hashable, so they can be dictionary keys
config_options = {
    frozenset(['read', 'write']): "Full Access",
    frozenset(['read']): "Read-Only Access"
}

user_permissions = frozenset(['read', 'write'])
print(f"Access level for {user_permissions}: {config_options[user_permissions]}")

# Frozensets can be elements of other sets
set_of_frozensets = {frozenset({1, 2}), frozenset({3, 4})}
print(f"Set of frozensets: {set_of_frozensets}")

# Comparison and set operations work as expected
print(f"Are fs1 and fs2 equal? {fs1 == fs2}")
fs3 = frozenset([3, 4, 5])
print(f"Intersection of fs1 and fs3: {fs1.intersection(fs3)}")
How it works: frozenset is an immutable version of Python's built-in set. Unlike regular sets, frozenset objects cannot be modified after creation (you cannot add or remove elements). This immutability makes them hashable, meaning they can be used as keys in dictionaries or as elements within other sets, which regular mutable sets cannot be. frozenset is particularly useful when you need a constant collection that can serve as a unique identifier or when you want to ensure the integrity of a set's elements throughout your program.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs