Sub topic 3
Frozensets and Tuples as Composite Keys
Assume you know variables, loops, functions, and basic Python types. This chapter focuses on choosing collections and avoiding reference-related bugs.
A dictionary key or set element must be hashable, meaning Python can calculate a stable hash for it. Immutable values such as strings, numbers, and tuples of hashable values are hashable. Lists and dictionaries are mutable, so they are not hashable.
A tuple can represent a fixed combination of values:
distances = {(52.5, 13.4): 8.2}
print(distances[(52.5, 13.4)])
permissions = {frozenset({"read", "write"}): "editor"}
print(permissions[frozenset({"read", "write"})])Use a frozenset when the elements form an unordered group. Use a tuple when position matters. A tuple is valid as a key only when every item inside it is hashable.
Common Pitfalls
Names refer to objects; assignment does not copy them.
original = [1, 2]
alias = original
alias.append(3)
print(original) # [1, 2, 3]
def add_item(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucketThe None pattern creates a fresh list for each call. A default such as bucket=[] creates one list when Python defines the function and reuses it.
Choosing a Collection
| Need | Collection |
|---|---|
| Ordered, changeable values | `list` |
| Fixed ordered values or a composite key | `tuple` |
| Lookup by named key | `dict` |
| Unique values or set algebra | `set` |
| Unordered group used as a key | `frozenset` |
Lists and tuples support indexing. Dictionaries provide key lookup. Sets provide membership tests and operations such as intersection. Choose immutability when the data should not change or must be hashable.
Specialized Alternatives
namedtuplegives tuple fields readable names.Countercounts hashable values.defaultdictsupplies a value for missing keys.dequesupports efficient additions and removals at both ends.
Exercise
Which collection should represent the unordered pair of users {"ana", "ben"} as a dictionary key?
Show answer
Use frozenset({"ana", "ben"}), because the pair is unordered and the key must be immutable and hashable.