Python Frozenset: Immutable Set Keys
Core idea
frozenset(values) creates an immutable collection of distinct hashable members. Like a set it supports membership and nonmutating group operations, but its members cannot be added or removed. Unlike an ordinary set, a frozenset is hashable, so it can be a dictionary key or an element in another set.
prices = {frozenset(["pen", "pad"]): 6}print(prices[frozenset(["pad", "pen"])])The order of the input labels does not affect the frozen-set key.
Separate a snapshot from its source
active = {1, 3}snapshot = frozenset(active)active.add(5)print(sorted(snapshot))print(5 in active)Later mutations to the original set do not change the frozen snapshot.
Reject mutation (intentional error)
This intentional error occurs because frozenset has no add method.
Common mistake
An ordinary set cannot be a dictionary key because it is unhashable. Do not rely on a particular numeric hash value for a frozenset.
Practice
Build a dictionary whose keys are frozensets of room labels. Look up a group in a different order and compare a group that has an extra member.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Frozenset
Check your understanding of frozenset.
What is printed?
print(frozenset([1, 2]) == frozenset([2, 1, 1]))What is printed?
d = {frozenset([2, 3]): 7}print(d[frozenset([3, 2])])What happens?
frozenset([1]).add(2)Why use frozenset for a dictionary key representing a group?