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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 13 views 0 copies

Python code

6 lines
Python 3.9+
frozen = 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

stdout
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

  1. Use frozenset(data) to create a frozen copy from any iterable like a tuple or list
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.