Sub topic 1
What a key-value mapping needs to do
Prerequisites
This chapter assumes you can:
- Write loops, functions, and classes in one language. The examples use Python.
- Index an array or list by position.
- Read introductory Big-O notation, such as O(1) and O(n).
- Use the integer modulo operator (
%).
No hashing knowledge is needed yet. This chapter defines the problem that hash tables solve. Later chapters build the solution.
The problem: look things up by name
A key-value mapping stores pairs. Each pair has a key and a value. The key identifies the entry, and the value is the data you want back. You ask the mapping for a key, and it returns the value stored under that key.
Mappings appear in many programs:
- A phone book maps names to numbers.
- A word counter maps each word to how many times it appeared.
- A session store maps a session ID to a user record.
- A compiler's symbol table maps variable names to their types.
Different languages use different names for this structure: dictionary, map, hash map, associative array, or object. They share the same contract, which this chapter calls a mapping. A hash table is one way to implement that contract. It is the most common way, but not the only one. Balanced search trees and sorted arrays also implement mappings.
Separating the contract from the implementation is useful. First you decide what the structure must do. Then you judge each implementation by how well it does that.
The core operations
A mapping needs a small set of operations.
| Operation | Meaning | Typical result |
|---|---|---|
| `put(key, value)` | Store a value under a key. If the key exists, replace its value. | Nothing |
| `get(key)` | Return the value stored under a key. | The value, or a default if absent |
| `remove(key)` | Delete the key and its value. | Whether something was removed |
| `contains(key)` | Report whether the key is present. | True or false |
| `len` | Report how many pairs are stored. | An integer |
Most libraries add iteration over keys, values, or pairs. That is a convenience built on the core set above, so this tutorial treats it as secondary.
Rules the contract must settle
The table above hides several decisions. Every mapping implementation must make them, and your code depends on the answers.
Keys are unique
A mapping holds at most one value per key. Calling put("apple", 4) after put("apple", 3) does not create a second entry. It replaces the first value. This is why put has to search for the key before it inserts. Even a simple implementation needs a lookup inside put.
Missing keys need a defined result
When get is called with an absent key, the mapping must do something predictable. Common choices are:
- Return a default value such as
None. Python'sdict.getdoes this. - Raise an error. Python's
d[key]raisesKeyError. - Return an "optional" wrapper, as Java's
Optionalor Rust'sOptiondo.
A default value of None creates an ambiguity. If None is also a legal stored value, the caller cannot tell "key absent" from "key present with value None". That is why contains exists as a separate operation.
Keys are compared by equality
The mapping decides whether two keys are "the same key" using an equality test. In Python, "app" + "le" == "apple" is true, so both strings find the same entry even though they are different objects in memory. The mapping must compare keys by value, not by object identity. This detail returns in the chapter on key requirements, where equality and hashing must agree.
Ordering is a separate promise
Does the mapping remember insertion order? Does it keep keys sorted? These are extra guarantees. A plain mapping contract promises neither. Python's dict preserves insertion order as a language guarantee since version 3.7. Many hash tables in other languages make no such promise. Do not depend on an order unless your language documents it.
A baseline: a list of pairs
Before building anything clever, write the simplest correct mapping. It stores pairs in a list and scans the list for every operation.
class ListMapping:
def __init__(self):
self._pairs = []
def put(self, key, value):
for i, (k, _) in enumerate(self._pairs):
if k == key:
self._pairs[i] = (key, value)
return
self._pairs.append((key, value))
def get(self, key, default=None):
for k, v in self._pairs:
if k == key:
return v
return default
def remove(self, key):
for i, (k, _) in enumerate(self._pairs):
if k == key:
del self._pairs[i]
return True
return False
def contains(self, key):
for k, _ in self._pairs:
if k == key:
return True
return False
def __len__(self):
return len(self._pairs)
m = ListMapping()
m.put("apple", 3)
m.put("pear", 5)
m.put("apple", 4)
print(m.get("apple"), m.get("fig"), len(m))
print(m.remove("pear"), m.remove("pear"))Running it prints:
4 None 2
True FalseCheck this against the rules above. The second put("apple", 4) replaced the first value, so keys stayed unique. get("fig") returned the default. The first remove("pear") reported success, and the second reported failure because the key was already gone. The class satisfies the contract.
Why the baseline is not good enough
Every operation scans the list. In the worst case that means comparing against all n stored keys. A lookup for a missing key always hits that worst case, because the scan cannot stop until it has checked every pair. So get, put, remove, and contains all cost O(n).
That cost compounds. Suppose you count words in a text with 100,000 distinct words. Each word requires one lookup, so the work grows roughly as the number of words times the number of distinct words. For large inputs the program becomes unusably slow.
Sorting the pairs and using binary search improves lookups to O(log n). But insertion and removal in a sorted array still shift elements, which costs O(n). Balanced trees reach O(log n) for all operations. A hash table aims for O(1) on average for all of them.
| Implementation | `get` | `put` | `remove` |
|---|---|---|---|
| Unsorted list of pairs | O(n) | O(n) | O(n) |
| Sorted array | O(log n) | O(n) | O(n) |
| Balanced search tree | O(log n) | O(log n) | O(log n) |
| Hash table | O(1) average | O(1) average | O(1) average |
The hash table row says "average" for a reason. Later chapters explain where the average comes from and when it fails.
The goal for the rest of the tutorial
The target is a structure where the work to find a key does not grow with the number of stored keys. To get there, you need a way to go from a key straight to a storage location, without comparing against every other key. Arrays already provide constant-time access by position. The remaining question is how to turn an arbitrary key, such as a string, into a position. The next chapters answer that question.
Common errors
- Treating
Noneas proof of absence. IfNonecan be a stored value, usecontainsor a unique sentinel object to detect missing keys. - Assuming order. Code that relies on iteration order breaks when the mapping type changes or the language does not guarantee order.
- Using mutable keys. A key whose content changes after insertion can no longer be found by equality. Later chapters explain why hashing makes this worse.
- Forgetting that
putreplaces. Counting code that callsput(word, 1)for every occurrence resets the count each time. You must read the old value first.
Exercise
A mapping stores the value None under the key "x". Calling get("x") returns None, and calling get("y") on an absent key also returns None. How can a caller tell the two cases apart, and why does the list-of-pairs baseline cost O(n) for a lookup of an absent key?
Show answer
The caller can use contains("x"), which returns True, and contains("y"), which returns False. Alternatively, pass a unique sentinel object as the default, such as get("y", sentinel), and check whether the result is that sentinel. The baseline scans every pair because an absent key can only be confirmed missing after all n keys have been compared against it, so the lookup does n comparisons.
Exercise
Using the ListMapping class, write the lines that count how many times each word appears in the list ["a", "b", "a"], so that the final count for "a" is 2.
Show answer
For each word, read the current count with a default of 0, then store the incremented count: m = ListMapping(); for w in ["a", "b", "a"]: m.put(w, m.get(w, 0) + 1). After the loop, m.get("a") is 2 and m.get("b") is 1. Reading before writing is needed because put replaces the old value.