Inside the table: insert and lookup
After this: Follow an insert and a lookup through the table, step by step.
On this page · 6 sections · 3 checks
You can now work out a key's slot: cat goes to slot 0. This lesson puts that to use. We store a pair in its slot, and then we find it again.
Two words will come up in every lesson from here. To means to store a pair in the table. A means giving the table a key and getting its value back.
The same path, twice
Take an empty table with eight slots, and insert cat with the value 3.
- Hash the key: the codes of
catadd up to 312. - Take the remainder: 312 % 8 = 0.
- Go to slot 0 and store the pair (
cat, 3).
Now look up cat.
- Hash the key: 312.
- Take the remainder: 0.
- Go to slot 0. The stored key is
cat, the key we asked for, so the answer is its value, 3.
The first two steps are the same both times. That is the reason a hash map is fast. A lookup does not search. It repeats the calculation of the insert, so it arrives at the same slot.
What about a key that was never inserted? Look up ant. Its codes add up to 323, and 323 % 8 = 3. Slot 3 is empty, so ant is not in the map. The answer is Nonenull, the marker for "nothing here". A missing key is a normal result, not an error.
Why a slot stores the key too
A slot holds the whole pair, not only the value. This may seem like a waste, since we already knew the key when we arrived. But a lookup needs the stored key to confirm that it has found the right thing. The next lesson shows what goes wrong without it.
The table in code
Python and Java do all of this for you and keep it hidden. So we will write a small version ourselves, called SimpleHashMap, where every step is visible. We add to it over the next three lessons. In this first version, each slot holds one pair.
In code, a slot is often called a . The two words mean the same thing, so the table is named buckets.
class SimpleHashMap: def __init__(self, capacity=8): self.capacity = capacity self.buckets = [None] * capacity # one pair per slot, for now
def _index(self, key): return sum(ord(ch) for ch in key) % self.capacity
def put(self, key, value): self.buckets[self._index(key)] = (key, value)
def get(self, key): pair = self.buckets[self._index(key)] if pair is not None and pair[0] == key: # same path, then confirm the key return pair[1] return Nonepublic class SimpleHashMap { private static class Pair { String key; int value; Pair(String key, int value) { this.key = key; this.value = value; } }
private final int capacity; private final Pair[] buckets; // one pair per slot, for now
public SimpleHashMap() { this(8); }
public SimpleHashMap(int capacity) { this.capacity = capacity; this.buckets = new Pair[capacity]; }
private int index(String key) { int sum = 0; for (char ch : key.toCharArray()) sum += ch; return sum % capacity; }
public void put(String key, int value) { buckets[index(key)] = new Pair(key, value); }
public Integer get(String key) { Pair pair = buckets[index(key)]; if (pair != null && pair.key.equals(key)) { // same path, then confirm the key return pair.value; } return null; }}Here is how to read it.
capacityis the number of slots, andbucketsis the table. Every slot starts empty.- _indexindex makes the two moves: it adds up the character codes and takes the remainder.
putis insert. It works out the slot and stores the pair there.getis lookup. The highlighted lines go to the slot, confirm that the stored key is the one we asked for, and return its value. If the slot is empty or holds another key, they return Nonenull.
m = SimpleHashMap()m.put("cat", 3)m.put("dog", 1)print(m.get("dog")) # slot 2, key matchesprint(m.get("ant")) # slot 3 is empty1 None
SimpleHashMap m = new SimpleHashMap();m.put("cat", 3);m.put("dog", 1);System.out.println(m.get("dog")); // slot 2, key matchesSystem.out.println(m.get("ant")); // slot 3 is empty1 null
Watch it happen
Here are four keys that land in four different slots, then a lookup that finds its key and one that does not. One step asks you to predict the slot first.
After each insert, the narration also gives a load factor. That number measures how full the table is. A later lesson explains it, so you can ignore it for now.
- Insert cat → 3Hash the key, go to the slot, and store the pair.
- Insert dog → 1
- Insert fox → 4
- Insert emu → 2
- Look up fox
- Look up ant
- 0—
- 1—
- 2—
- 3—
- 4—
- 5—
- 6—
- 7—
Start with the first task above, or try any key.
- count
- 0
- load
- 0.00
- compares
- 0
Check yourself
After inserting cat, dog and fox, which slot holds dog? (d = 100, o = 111, g = 103)
A lookup has worked out the slot. What does it do before it returns a value?
What does this print?
m = SimpleHashMap()m.put("cat", 3)print(m.get("ant"))SimpleHashMap m = new SimpleHashMap();m.put("cat", 3);System.out.println(m.get("ant"));Connect
This is what your language's hash map does when you write these familiar lines. The real versions differ in some details, and the honesty notes in later lessons say how, but the path is the same.
d = {}d["cat"] = 3 # hash "cat", go to its slot, store the pairprint(d.get("cat")) # same path, confirm the key, return 3print(d.get("ant")) # None: nothing stored under that keyMap<String, Integer> d = new HashMap<>();d.put("cat", 3); // hash "cat", go to its slot, store the pairSystem.out.println(d.get("cat")); // same path, confirm the key, return 3System.out.println(d.get("ant")); // null: nothing stored under that key- Follow an insert: hash the key, go to the slot, store the pair.
- Follow a lookup: hash the key, go to the slot, confirm the key, and return the value or the missing marker (None in Python, null in Java).
- Say why the pair stores the key as well as the value.