Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Data Structures

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Data Structures

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.

Names filed by their first letter tabs 0 to 3tab 4 (E)tabs 5 to 8tab 9 (J)tab 19 (T) EmmaJackJaneTom get("Jane"): jump to tab 9, check Jack, check Jane ord("J") - ord("A") = 9
Jack and Jane collide on tab 9 and share a short list. Emma and Tom are never looked at.

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

OperationUsual costWorst case
putO(1)O(n) if everything piles onto one tab
getO(1), a jump then a few checksO(n), reading one long list
Add tabs and refileO(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.

Keep going in Data Structures and Algorithms · 6 of 21

Previous
Queues: First In, First Out, With a Ring of Cells
Next post
Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • Emma's phone contacts
  • An address book with tabs
  • Inside PhoneBook
  • Put four, get one
  • When one tab gets crowded
  • Python's own: dict
  • A jump, then a few checks
  • Where you meet a hash table
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.