Hashing and Dictionaries/Sets

Lesson 13 of 20

Follow one key through hash, bucket and chain — then watch a set intersect two lists in O(1) probes per item.

The big picture

Meet the hash table

A dict finds any value in one hop: the key is hashed, the hash picks a bucket, and the walk is short. That trick powers half of Python problem solving.

The hash table

dict is a hash table: key → hash → bucket → value. Average lookup, insert and delete are all O(1).

Collisions happen

Two keys can land in one bucket. Python chains them — the walk gets longer, but lookups stay correct.

dict idioms

counts.get(ch, 0) + 1, "k" in d and d.items() — the everyday frequency-counting toolkit.

Sets = keys only

A set is a dict without values: unique items, O(1) membership, union |, intersection &.

Hashable rules

Keys must be immutable: strings, numbers and tuples qualify — lists and dicts are not hashable.