Frozensets as Keys and Elements

Concepts covered: Frozensets

Some facts describe a group rather than a sequence: the products bought together in an order, the 2 accounts on either end of a transfer, the permissions a role holds. Counting or looking up a group needs a key that ignores order and repeats. A list cannot be a dict key at all. A tuple can, but it treats ("SKU-12", "SKU-40") and ("SKU-40", "SKU-12") as different keys. A frozenset is hashable, ignores order and collapses repeats, which matches what a bundle is.

orders = [
    ["SKU-12", "SKU-40"],
    ["SKU-40", "SKU-12"],
    ["SKU-12", "SKU-40", "SKU-12"],
    ["SKU-07"],
]
by_tuple = {}
by_frozen = {}
for basket in orders:
    t = tuple(basket)
    by_tuple[t] = by_tuple.get(t, 0) + 1
    f = frozenset(basket)
    by_frozen[f] = by_frozen.get(f, 0) + 1
print(len(by_tuple), len(by_frozen))
for bundle, n in by_frozen.items():
    print(sorted(bundle), n)

Output:

4 2
['SKU-12', 'SKU-40'] 3
['SKU-07'] 1

The tuple keys found 4 bundles where the business sees 2, because each ordering and the repeated SKU-12 produced a key of its own. The frozenset keys merged all 3 baskets that contain SKU-12 and SKU-40. tuple(sorted(basket)) fixes the ordering but still splits the third basket on its duplicate. Whether collapsing repeats is correct depends on the question being asked. For "which products sell together" it is. For "which exact orders recur", 2 units of SKU-12 differ from 1, and the key has to carry the quantity.

Key built from a basketIgnores orderIgnores repeatsHashable
list(basket)NoNoNo
tuple(basket)NoNoYes
tuple(sorted(basket))YesNoYes
frozenset(basket)YesYesYes
frozenset(Counter(basket).items())YesNo, keeps each countYes

Lookups need a frozen key too

A dict hashes the value used to look it up, so the query must be hashable as well. Code that gathers a basket into a set and tests it against a frozenset-keyed dict fails with TypeError. The same test against a set of frozensets succeeds. Set membership, remove and discard catch the error and retry with a temporary frozenset built from the argument. Dicts have no such retry.

bundle_counts = {frozenset({"SKU-12", "SKU-40"}): 3}
known_bundles = {frozenset({"SKU-12", "SKU-40"})}
basket = {"SKU-40", "SKU-12"}

bundle_counts[frozenset(basket)]   # 3
basket in known_bundles            # True: the set retries as a frozenset
basket in bundle_counts            # TypeError: unhashable type: 'set'

functools.lru_cache follows the same rule, because it keys its cache on the call's arguments. A cached function called with a set raises TypeError: unhashable type: 'set' before the function body runs. Passing frozenset(skus) fixes it, and calls with the same SKUs in any order share 1 cache entry.

Sets whose elements are sets

Hashability also lets a frozenset be an element, which gives a set of groups. Undirected pairs are the standard case. A transfer from acct_1 to acct_2 and a transfer from acct_2 to acct_1 describe a single relationship, and frozenset((src, dst)) gives both of them the same identity.

transfers = [("acct_1", "acct_2"), ("acct_2", "acct_1"), ("acct_3", "acct_1")]
pairs = set()
for src, dst in transfers:
    pairs.add(frozenset((src, dst)))
print(len(pairs))   # 2

Frozensets can also contain other frozensets. A fixed collection of groups, such as the bundles in this week's promotion, can therefore itself be a key or an element.

Build mutable, freeze, thaw

Real workflows need both types at different moments. While events stream in, each session's cart has to grow, which takes a set. When the stream ends, the finished cart has to become a key, which takes a frozenset. frozenset(cart) copies the current elements into a new immutable object, and later changes to cart never reach it. In the other direction, set(bundle) returns a mutable copy to edit while the frozen original stays in the dict. Each conversion copies every element, so convert once at the boundary between stages and never on every event.

Each stage holds the type that matches what it does to the data. A cart that starts as a frozenset fails on its first .add, and a cart that reaches the dict while still a set fails as a key. The conversion belongs at the point where accumulation ends and counting begins.

About this lesson

This section is part of the Sets: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.