Hash Codes and Hash Functions
A hash table stores key/value pairs in an array and uses the key to find where a pair is stored, avoiding a scan through unrelated items when the table works well.
Try it: How a dict Stores Keys
How a dictionary turns a key into a slot with a hash, what happens on a collision, why deleted keys leave a marker, and why the table grows.
How it works
- hash(key) gives a number; hash % table size gives the key's home slot.
- If that slot is taken by another key (a collision), probe the next slot.
- Deleting leaves a DELETED marker so lookups keep probing past it.
- When more than 2/3 of the slots are used, the table doubles and every key is re-inserted.
Default run (5 steps): A dict with 3 keys in 8 slots. Choose an operation. Example: d["mango"] = 5. … Done. 4 keys in 8 slots.
Simplified: Uses a small educational hash (Python's real string hash is randomised per run) and simple linear probing; CPython's probe order is more elaborate.
Loading the simulation…
Finding a Record Without Scanning the List
Imagine you keep a list of student records, and each record is tied to a student ID. If someone asks for the record of one particular ID, the simplest approach is to start at the beginning of the list and check each record until you find a match. That approach works, but the time it takes grows as the list grows. A hash table is a structure designed to answer the question, given a key, without that long scan.
A hash table stores key/value pairs, the same kind of data a HashMap holds. You can also use a hash table to implement a set. In a set there are no values, so the only question is whether a key is present. Either way, the central task is the same: given a key, find out where its information lives.
What do you think happens?
If a list holds a million records and you search it from the beginning, roughly how many records might you have to check before finding the one you want?
Reveal answer
In the worst case, all of them, and on average about half, because an unsorted list may require checking many unrelated items before reaching the right one.
The source contrasts this with a hash table, which tries to remove the searching entirely by letting the key itself point to a location.
Direct Indexing and Its Limits
Suppose every key were a whole number from 0 to 99. Then you could reserve an array of 100 slots and store each pair in the slot whose index equals its key. Finding a pair would require no search at all. The pair for key 42 would sit in slot 42, and you would simply read that slot.
This idea breaks down quickly for realistic keys. An int can take a very large number of values, so an array with one slot for every possible int would be enormous, even if you only plan to store a few thousand items. If keys are strings of arbitrary length, the number of possible keys has no limit, and one slot per key cannot be built at all. The direct-indexing idea is good, but the array has to be much smaller than the set of possible keys. That tension is what hash tables resolve.
Roles of the Key, Hash Function, and Hash Code
A hash table stores its data in an array, but the array index for a key is not the key itself. Instead, the index is computed from the key. A hash function is the piece that performs this computation: it takes a key and produces a hash code. The number that a key produces this way is its hash code, and a hash code is the array index where that key is stored.
The flow of a lookup runs in one direction. You start with the key you are looking for, pass it through the hash function, obtain a hash code, and go straight to that array location. The hash function is the only piece that knows how the key maps to a position, so the rest of the table never needs to inspect the other stored items to find the right one.
Because the lookup depends only on the key, the same key always produces the same hash code, and therefore the same array location. That repeatability is what lets you find a pair again later without searching for it.
The source describes the hash table approach as going directly to the place where the item is stored, with a caveat: this is close to true only when the hash table is working properly. Some extra checking can still happen inside a single location, which is discussed in the collisions section below.
Tracing a Lookup Through the Table
Looking Up a Key in a Five-Slot Table
A table has an array of five slots, numbered 0 to 4. Pairs are stored under the keys "Ana", "Ben", and "Cal". Assume the hash function sends "Ana" to hash code 1031, which the table uses as its index. Trace how a lookup for "Ana" proceeds. This example is illustrative and does not describe any particular real hash function.
- 1Start with the key
The lookup begins with the key "Ana". No other stored item is examined yet.
- 2Compute the hash code
The hash function processes "Ana" and produces hash code 1031.
- 3Use the index
The hash code gives the array location where "Ana" was stored. The table goes straight to that location.
- 4Compare the key
The table checks that the stored key at that location is "Ana". If it matches, the value is returned.
The value for "Ana" is found after one hash computation and one direct access, without scanning "Ben" or "Cal".
The source pack does not detail how a large hash code is reduced to fit the size of a particular array, even though the array is much smaller than the set of possible keys. It describes the hash code as the array index. If you want the exact mechanism a specific language uses, consult that language's documentation.
Collisions: Two Keys, One Hash Code
The array has fewer locations than there are possible keys, so it is possible for two different keys to produce the same hash code. When that happens, both keys want the same array location. This situation is called a collision. The source is clear that a collision is not an error. A hash table cannot reject a key simply because another key already produced the same hash code. It has to be able to store both in some reasonable way.
The approach described for the Java style of hash table is to let each array location hold a linked list of key/value pairs. The list may be empty. When two items share a hash code, they both belong to the same linked list at that location.
In this illustration, slot 2 holds two pairs because "Ana" and "Ben" produced the same hash code. The other slots hold zero or one pair each, which is the typical situation when the table works well. The collision is visible only as a location with several pairs.
What do you think happens?
If "Ben" is looked up in the table above, what must the table do once it reaches slot 2?
Reveal answer
It must check the keys in the list at slot 2, compare them to "Ben", and return the value 91 when it finds the matching key.
The hash code only identifies the location. Because that location may hold several pairs, the keys themselves are what distinguish them.
What Collisions Cost a Lookup
A hash code still tells you the array location, but that location may now hold several pairs. You must then check the keys in that list to find the one you want. Collisions therefore keep the table correct, at the cost of some extra checking inside a single location. If the hash table is working properly, that extra checking stays small. This is why the direct-access idea is described as close to true rather than exactly true.
Common Misunderstandings About Hash Tables
Common mistake Assuming the key itself is the array index
Why it failsThe source states that the index is computed from the key by a hash function. The key is not used directly as the index, which is what makes direct indexing impractical for realistic keys.
Do this insteadTreat the hash code, produced from the key by the hash function, as the index.
Common mistake Thinking a collision means the table has a bug
Why it failsBecause the array has fewer locations than possible keys, two keys can legitimately share a hash code. The source says a collision is not an error.
Do this insteadExpect collisions and rely on the structure at each location, such as a linked list, to store both pairs.
Common mistake Believing a lookup never compares keys
Why it failsWhen a location holds several pairs, the stored keys must be compared to tell them apart.
Do this insteadAfter jumping to the location, compare keys until the matching pair is found.
Practice Tracing Keys to Slots
A hash table with five slots stores "Eve" in slot 3 alone and places "Fay" and "Gus" together in slot 0. Describe the lookup for "Gus" step by step, naming the hash code and array index you would use, and state what happens when the table reaches slot 0.
Hints
- Start with the key "Gus" and identify which stage of the pipeline comes first.
- Remember that the hash code is the array index for the key.
- Slot 0 holds two pairs, so think about how the keys are compared inside that location.
Summary of the Hash Table Mechanism
- 1A hash table stores key/value pairs in an array and uses the key to find where a pair is stored, avoiding a scan through unrelated items when the table works well.
- 2A hash function computes a hash code from the key, and that hash code is the array index where the key is stored.
- 3Direct indexing fails for realistic keys because the number of possible keys is far larger than any practical array, so the array must be smaller than the key space.
- 4A collision occurs when two keys produce the same hash code. It is not an error, and each array location can hold a linked list of pairs so that colliding keys are stored and told apart by their keys.
At a glance
- A hash table locates a key/value pair by computing its array index from the key, so it does not need to check every stored item when the table works well.
- The key goes through a hash function to produce a hash code, and the hash code is the array index where the pair is stored.
- Two different keys can produce the same hash code, creating a collision that is normal and not an error.
- Each array location can hold a linked list of pairs, so colliding keys share a location and are distinguished by comparing their keys.