Code

Buckets & Collisions

How does a dict find a key instantly, even among a million? It's a hash table. Let's build a tiny one to see the trick.

The idea

  1. Keep a list of buckets (each bucket is a small list).
  2. hash(key) turns the key into a big integer.
  3. hash(key) % len(buckets) picks a bucket index.
  4. Store the (key, value) pair in that bucket.
buckets = [[] for _ in range(4)]
index = hash("oil") % 4      # some number 0..3
buckets[index].append(("oil", 5))

Collisions

Two different keys can land in the same bucket, a collision. That's fine: the bucket holds several pairs, and we scan just that one small bucket comparing keys with ==. With enough buckets, each holds only a few pairs, so lookups stay O(1) on average. (Real dicts also grow their table as they fill up.)

Pip tip: This is why dict keys must be hashable (like str, int, tuple). A list can change, so its hash would change too and it would get lost in the wrong bucket!

Assignment

Finish LanternTable:

  1. put(key, value): if the key is already in its bucket, replace that pair with (key, value). Otherwise append the new pair and add 1 to self.count.
  2. get(key, default=None): return the value stored for key, or default if it isn't there.
  3. Store pairs as (key, value) tuples inside self.buckets. No dicts allowed inside the table!