Data structures · Lesson 8 of 18 · 18 min

Mappings and sets

Dicts, hashing, set algebra, and insertion order.

  • Use dicts as the default record type
  • Understand hashability
  • Apply set operations to membership problems

Dicts remember insertion order

Since Python 3.7, a dict is an ordered mapping: iterating `d`, `d.keys()`, `d.values()`, and `d.items()` follows insertion order. `d[key] = value` updates in place without moving the key; deleting and reinserting sends it to the end.

Keys must be hashable: their hash is stable for the lifetime of the object. That is why lists cannot be keys and why you must not mutate an object after using it as a key. Strings, numbers, and frozensets are the usual keys. Tuples work if every element is hashable.

get, setdefault, and unpacking
counts = {"a": 1}
print(counts.get("b", 0))
counts["b"] = counts.get("b", 0) + 1
print(counts)
counts.setdefault("c", []).append("x")
print(counts)
merged = {**{"a": 1, "b": 2}, **{"b": 9, "c": 3}}
print(merged)

Sets are unique and unordered

A set is a hash table of unique, hashable elements. Use it for membership tests, deduplication, and algebra: `|` union, `&` intersection, `-` difference, `^` symmetric difference. Membership is average O(1).

`frozenset` is the immutable twin — it can live inside another set or as a dict key. Empty set syntax is `set()`, not `{}` (that is an empty dict).

Set algebra
py = {"def", "class", "for"}
js = {"function", "class", "for"}
print("both:", py & js)
print("python only:", py - js)
print("either:", py | js)
print("one or the other:", py ^ js)
print(set("book"))

Check yourself

Quiz

  1. 1.What is `{}`?

  2. 2.Which can be a dict key?

  3. 3.`{**a, **b}` when keys overlap:

Practice

Exercise

Write `word_set(text)` that returns the set of lowercased words in text (split on whitespace), and `shared(a, b)` that returns the sorted list of words in both sets.

Tutor

Ask a question about this lesson. Answers are generated on demand and capped so the session stays focused.