In this lesson, you will learn how to create unchangeable collections using frozenset to ensure your data remains stable and usable as dictionary keys.
Why Immutability Matters for Sets
As we have explored, standard sets are mutable; you can add or remove items at will. However, because they are mutable, they are not "hashable." If you try to use a standard set as a key in a dictionary or as an element inside another set, Python will raise a TypeError. This is because a hash table requires the key to have a fixed hash value, which is impossible if the contents of that key can change.
Introducing the frozenset
A frozenset is the immutable counterpart to a standard set. Once you create it, you cannot add, remove, or modify its elements. Because the content is locked in, the object’s hash value remains constant, making it perfectly safe to use as a dictionary key.
Consider this example where we track inventory categories:
# A standard set would fail as a dictionary key
# We use frozenset to make the collection "fixed"
category_group = frozenset(['electronics', 'gadgets'])
# Now we can use it as a key in our inventory system
inventory_map = {
category_group: "Warehouse A",
frozenset(['books', 'stationery']): "Warehouse B"
}
# We can safely retrieve the data
print(inventory_map[frozenset(['electronics', 'gadgets'])])
When to use it
Think of frozenset as a "read-only" snapshot of your data. You should reach for it whenever you need to group items together but must guarantee that the collection will never change throughout the execution of your program. This is particularly useful when representing complex, multi-item keys in a dictionary or when you want to store a collection of unique groups within another set. Since frozenset is immutable, it is inherently hashable, allowing it to fit into the structures that standard sets simply cannot occupy.
Key Takeaway: Use frozenset when you need an immutable, hashable collection that can act as a dictionary key or an element within another set.