Hash Tables: The Name Tells You Where to Look
A hash table turns a name into a bucket number, so you jump straight to the right place. Build Emma's phone book in Python with 26 letter tabs, watch Jack and Jane collide on tab 9, see why piling names onto one tab is the slow case, and meet Python's dict, which does it properly.
What you will learn
- Explain hashing, buckets and collisions with an address book
- Build a small hash table in Python with 26 letter tabs
- Explain why a crowded bucket slows lookups and how a better hash and more buckets fix it
- Use Python's dict as a ready-made hash table
Before you start
- Python lists and classes
- Big-O basics
A hash table finds things in about one step. The idea is very simple: the name itself tells you which tab to open.
Emma's phone contacts
Emma has a thousand contacts on her phone, and she wants Jane's number. The slow way is to check them one by one. Anna? No. Ben? No. That can take a thousand checks for one name. What you want is to jump straight to Jane, check Jack, then Jane, and have her number in two checks.
An address book with tabs
Picture an address book with letter tabs, A to Z. Every name goes under its first letter: Emma under E, Tom under T, Jack under J. To find Jane you don't read A to I; you open the J tab straight away. On page J there are Jack and Jane, so you check just those two names.
A few words for this. The rule that turns a name into a tab number is called hashing; here the rule is the first letter. A tab is also called a bucket. Two names on one tab is a collision. The name tells you where to look, and that's a hash table.
Inside PhoneBook
from dataclasses import dataclass
@dataclass
class Contact:
name: str
phone: str
class PhoneBook:
def __init__(self):
self.tabs = [[] for _ in range(26)]
def tab_of(self, name):
return ord(name[0]) - ord("A")
def put(self, name, phone):
t = self.tab_of(name)
self.tabs[t].append(Contact(name, phone))
print(name + " -> tab " + str(t))
def get(self, name):
for c in self.tabs[self.tab_of(name)]:
print(" check " + c.name)
if c.name == name:
return c.phone
return None
Contact is just a name and a phone number. tabs is 26 empty lists, one per letter. tab_of is the heart of it: the first letter minus capital A, so A is 0, B is 1 and J is 9. put finds the tab and adds the contact to that list. get opens one tab and checks only the names inside it. It never loops over every contact.
Put four, get one
from phone_book import PhoneBook
book = PhoneBook()
book.put("Emma", "555-0101")
book.put("Jack", "555-0102")
book.put("Tom", "555-0103")
book.put("Jane", "555-0104")
print("Jane: " + book.get("Jane"))
Emma -> tab 4
Jack -> tab 9
Tom -> tab 19
Jane -> tab 9
check Jack
check Jane
Jane: 555-0104
Emma goes to tab 4, Jack to 9, Tom to 19. Jane is J again, tab 9, but Jack is already there. That's a collision, and it's no problem: Jane just joins the same list, after Jack. To get Jane you jump straight to tab 9, check Jack (not her), then Jane. Found in two checks.
When one tab gets crowded
There's a catch. This rule looks only at the first letter, and lots of names start with J. Put Jack, Jane, Jill, Joe and Jess, and all five land in tab 9. Getting Jess means checking Jack, Jane, Jill, Joe and finally Jess: five checks. If all thousand contacts landed in one tab, you'd be back to reading them one by one.
So the jump is only as good as the rule that spreads the names out. There are two fixes.
First, a better rule. Instead of the first letter, mix all the letters together: give each letter its place in the alphabet, add them up, and keep the remainder after dividing by the number of tabs. With a rule like that, names that start the same no longer land together. In the course's example, the same twelve names that piled eight deep onto tab J spread out so the longest list holds just three.
Second, add tabs as the book fills up. When the book gets about three quarters full, it doubles the number of tabs and files every name again with the new count. That takes a moment, but it happens only once in a while, just like a dynamic array growing. The book gets bigger, but the lists don't get longer.
Python's own: dict
The good news is that Python already has a hash table for you:
book = {}
book["Emma"] = "555-0101"
book["Jack"] = "555-0102"
book["Tom"] = "555-0103"
book["Jane"] = "555-0104"
print("Jane: " + book.get("Jane"))
Jane: 555-0104
Same four puts, same answer. A dict doesn't use just the first letter. It uses a hash, a number made from the whole key, and it adds more room as it fills up. So lookups need about one check. (CPython handles collisions by trying another slot rather than keeping a list per bucket, but the idea is the same.) A set works the same way, which is why the guest book in the Big-O lesson was so fast.
A jump, then a few checks
| Operation | Usual cost | Worst case |
|---|---|---|
| put | O(1) | O(n) if everything piles onto one tab |
| get | O(1), a jump then a few checks | O(n), reading one long list |
| Add tabs and refile | O(n), but rare |
A good rule and a roomy book keep every list short, so the book never slows down as it grows.
Where you meet a hash table
Contacts and user accounts are looked up by name. A spell checker asks whether a word is in the dictionary in one jump. A cache finds a page you opened before by its address. And counting words in a text gives each word its own spot holding its count, which in Python is a dict or a Counter.
Recap
- A hash table is a row of buckets. A rule turns the key into a bucket number, so put and get jump straight there.
- Keys in the same bucket share a short list. That's a collision, and it's normal.
- It slows down only when the rule piles keys onto one bucket, so use the whole key and add buckets as it fills.
Try it yourself: in contacts_app.py, put James as well, and predict which lines get("James") prints before you run it.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
What a Data Structure Is, and How Memory Works
Memory is a long row of numbered boxes, and opening any box is equally quick. A data structure is an agreed way of arranging things in those boxes, plus a few small notes. See with six songs on a phone why every structure is quick at some things and slow at others.
Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
A fixed array never gets longer. A dynamic array fills its box, then copies everything into a box twice the size. Build one for Emma's playlist in Python, count the copies and shifts, and see why adding at the end stays cheap while inserting at the front costs almost 50 million shifts for 10,000 songs.
Linked Lists: A Chain of Clues, Built in Python
In a linked list every node holds a value and the address of the next node. Build a treasure hunt chain in Python: a new first clue is two moves at any size, slipping a clue in or out is just changing next, but reaching clue number i is a walk of i hops.
Stacks: Last In, First Out, With the Undo Button
A stack is last in, first out: the newest thing you put on is the first thing you take off. Build Emma's undo button in Python from a list and one top index, push, pop and peek in one step each, undo after a million edits, and see what happens when you pop an empty stack.
