Sub topic 1
What a Key-Value Mapping Needs to Do
A key-value mapping stores values and lets you find each one by a key you choose, such as a username, a word, or a product ID. Other names for it are associative array, dictionary, and map. A hash table is one way to build it. This chapter defines what the mapping must do, so that later chapters can show how a hash table does it quickly.
Prerequisites
You should be comfortable with the following:
- Basic Python: loops, functions, and classes.
- Lists and indexing by position.
- Introductory Big-O notation, such as O(1) and O(n).
- The integer modulo operator (
%).
The Contract
A mapping is defined by its operations, not by how it stores data. Any implementation must provide these:
| Operation | Meaning | Behavior to decide |
|---|---|---|
| `put(key, value)` | Associate a value with a key | Writing an existing key replaces its value |
| `get(key)` | Return the value for a key | Return a default or raise an error if the key is missing |
| `remove(key)` | Delete a key and its value | Report whether anything was removed |
| `contains(key)` | Test whether a key is present | Must not change the mapping |
| `len` | Count the stored pairs | Counts keys, not writes |
Two rules matter most. Each key appears at most once, and lookup depends only on the key, never on position or insertion order. Two keys that compare equal must be treated as the same key.
A Naive Implementation
The simplest way to meet the contract is a list of pairs that we scan on every call.
class ListMap:
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 __len__(self):
return len(self._pairs)
m = ListMap()
m.put("apple", 3)
m.put("pear", 5)
m.put("apple", 4)
print(m.get("apple"))
print(len(m))
print(m.get("plum", "missing"))This prints 4, 2, and missing. The overwrite of "apple" left only two pairs, so the uniqueness rule holds.
Where the Naive Version Fails
Every operation scans the list from the start. A lookup for a missing key compares against all n pairs, so each operation costs O(n). With a million entries, a million lookups can mean on the order of a trillion comparisons.
A plain array does not have this problem when you index by position. items[7] jumps straight to its slot in O(1). The goal of a hash table is to give keys the same direct jump.
Common Errors to Avoid
- Assuming order. The contract promises lookup by key, not any ordering of keys. Some libraries add insertion order, but the idea of a mapping does not require it.
- Confusing a missing key with a stored
None.getreturningNoneis ambiguous, so providecontainsor a default argument. - Using keys that change. If a key's equality changes after insertion, the mapping can no longer find it. Later chapters explain why.
Exercise
In ListMap, what is the worst-case number of key comparisons for get on a mapping with n pairs, and which input produces it?
Show answer
n comparisons. A key that is absent, or one stored in the last position, forces the loop to compare against every pair before it returns.