How to Use a Frozenset as a Dict Key in Python
Demonstrates using an immutable frozenset as a hashable dictionary key, including equality and lookup with differently-ordered elements.
Python code
6 linesfrozen = frozenset({"a", "b", "c"})
mapping = {frozen: "set as hashable key"}
other_frozen = frozenset(["c", "b", "a"])
print(f"Are keys equal? {frozen == other_frozen}")
print(f"Lookup with different order: {mapping[other_frozen]}")
print(f"Hash matches: {hash(frozen) == hash(other_frozen)}")
Output
Are keys equal? True
Lookup with different order: set as hashable key
Hash matches: True
How it works
A frozenset is an immutable set, so it is hashable and can be used as a dictionary key. Because sets are unordered, two frozensets with the same elements are considered equal, regardless of insertion order. The hash of a frozenset is order-independent and matches for equal frozensets. This lets you store cached results or groupings keyed by an unordered collection of values.
Common mistakes
- Trying to use a regular mutable set as a dict key — raises TypeError: unhashable type
- Assuming order affects equality or lookup — frozensets compare by element content, not position
- Forgetting that frozenset is required for hashability, unlike set which is mutable
Variations
- Use frozenset(data) to create a frozen copy from any iterable like a tuple or list
- Leverage dict.get() to safely retrieve values when the key might not exist
Real-world use cases
- Caching memoized results keyed by combinations of input parameters that have no natural order.
- Grouping records by a bundle of features or tags stored as a frozen set in an aggregation pipeline.
- Building a lookup table for user permission sets where role membership ordering is irrelevant.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.