Python Tutoring Online
 Home

Python Hash Table: How Dictionaries Work Internally

A hash table is the underlying data structure that powers Python dictionaries. It allows Python to store and retrieve values extremely quickly using keys, without ever needing to scan through every item in the collection. Because dictionaries — and sets — are built directly on top of hash tables, most of their operations run in close to constant time, no matter how large the collection grows.

Instead of searching through all elements one by one, a hash table calculates the location of a value using a mathematical function called a hash function. This makes lookup, insertion, and deletion operations extremely fast even when the dataset contains millions of entries. This guide walks through exactly how that works, from the hash function itself to collision handling and a hands-on simulation you can run yourself.

Need Help Learning Python?

Understanding hash tables helps explain why Python dictionaries are so powerful and efficient.

Many advanced programming systems such as databases, caches, and indexing systems also rely on hash tables.

Get Python Tutoring Help

What Is a Hash Table?

A hash table is a data structure that stores data as key-value pairs. Each key is processed by a hash function that converts the key into a numeric value called a hash.

This hash value determines where the corresponding value will be stored in an underlying array in memory. Because the storage location is calculated directly from the key rather than discovered by searching, Python can retrieve values without scanning the entire data structure — this direct-access property is the entire reason hash tables are fast.

The Role of the Hash Function

A hash function converts a key into an integer. Python provides the built-in hash() function, which you can call directly to see the hash value of any hashable object.

Python
key = "apple"

print(hash(key))

Output


-842391234567...

The number produced by the hash function helps determine where the key-value pair will be stored in the hash table. A good hash function has two important properties: it's fast to compute, and it spreads different keys across different positions as evenly as possible, minimizing the chance that two keys land in the same spot.

How Python Stores Data in a Dictionary

When a key-value pair is added to a dictionary, Python performs the following steps internally.

Python
data = {}

data["name"] = "Alice"
data["age"] = 21
data["course"] = "Python"

print(data)

Output


{'name': 'Alice', 'age': 21, 'course': 'Python'}

How Dictionary Lookup Works

When Python needs to retrieve a value from a dictionary, it recalculates the hash of the key being looked up. This hash points directly to the slot where the value should be stored, so Python can jump straight there instead of checking every entry.

Python
student = {
"name":"Alice",
"age":21,
"course":"Python"
}

print(student["course"])

Output


Python

Because Python knows almost exactly where the value is stored, lookup operations are extremely fast — this is the mechanism behind the O(1) average-case complexity dictionaries are known for.

Hash Collisions

A hash collision occurs when two different keys produce the same hash value, or when two different hashes map to the same slot in the underlying table. Although collisions are relatively rare with a well-designed hash function, they are mathematically inevitable once enough keys are stored, since a finite table has fewer slots than the number of possible hash values.

Python dictionaries handle collisions internally using a strategy called open addressing with probing: when a slot is already occupied, Python calculates an alternative nearby slot to check next, following a specific probing sequence until it finds either the matching key or an empty slot. This ensures every value can still be stored and retrieved correctly, even when collisions occur — collisions add a small amount of extra work but don't break the data structure.

Why Dictionary Keys Must Be Immutable

Dictionary keys must be immutable (and therefore hashable) objects such as strings, integers, floats, or tuples of immutable values. This requirement exists because the hash value calculated for a key must remain constant for as long as that key lives in the dictionary.

If a key's hash could change after it was inserted, Python would look in the wrong slot the next time it tried to find that key — the value would effectively become lost, even though it's still technically stored somewhere in memory. Immutability guarantees this can never happen.

Python
data = {
"name":"Alice",
"age":21
}

print(data["name"])

Output


Alice

Strings are immutable, which means their content — and therefore their hash value — never changes after creation, making them safe and reliable as dictionary keys.

Example of an Invalid Dictionary Key

Python
data = {}

key = [1,2,3]

data[key] = "value"

Output


TypeError: unhashable type: 'list'

Lists cannot be used as dictionary keys because they are mutable — their contents can change after creation, which means their hash value could change too. Python prevents this outright by making lists (and other mutable types like dicts and sets) unhashable, raising a TypeError rather than risking silent, hard-to-debug lookup failures.

Which Types Are Hashable in Python?

Understanding which built-in types can and cannot be used as dictionary keys avoids a lot of confusion. The table below summarizes the most common types.

Type Hashable? Can Be a Dict Key?
str Yes Yes
int / float Yes Yes
tuple (of hashable items) Yes Yes
frozenset Yes Yes
list No No
dict No No
set No No

Note that a tuple is only hashable if every element it contains is itself hashable — a tuple containing a list, for example, is not hashable and cannot be used as a key.

Python
valid_key = (1, 2, 3)
data = {valid_key: "ok"}
print(data)

invalid_key = (1, [2, 3])
data[invalid_key] = "fails"

Output


{(1, 2, 3): 'ok'}
TypeError: unhashable type: 'list'

Advantages of Hash Tables

Disadvantages and Limitations of Hash Tables

Simple Demonstration of a Hash Table

The following example shows a very simplified simulation of how a hash table might store values, using the modulo operator as a basic hash function to map a key into a fixed-size array.

Python
size = 10
table = [None] * size

def simple_hash(key):
    return key % size

index = simple_hash(25)

table[index] = "Stored Value"

print(table)

Output


[None, None, None, None, None, 'Stored Value', None, None, None, None]

The hash function 25 % 10 = 5 determines that the value should be stored at index 5. Real hash tables use far more sophisticated hash functions and collision-resolution strategies than this simple example, but the core idea — calculating a slot directly from the key — is exactly the same principle Python's dictionaries rely on.

Extending the Simulation: Handling a Collision

This example builds on the simulation above to show what happens when two different keys hash to the same slot, using simple linear probing to resolve the collision.

Python
size = 10
table = [None] * size

def simple_hash(key):
    return key % size

def insert(table, key, value):
    index = simple_hash(key)
    while table[index] is not None:
        index = (index + 1) % len(table)
    table[index] = (key, value)

insert(table, 5, "First")
insert(table, 15, "Second")

print(table)

Output


[None, None, None, None, None, (5, 'First'), (15, 'Second'), None, None, None]

Both 5 and 15 hash to index 5 using key % 10, creating a collision. The insert() function detects that slot 5 is already taken and probes forward to the next open slot — index 6 — to store the second value. This is the same fundamental idea behind how CPython resolves collisions internally, though its actual probing sequence is considerably more sophisticated.

Real World Uses of Hash Tables

Hash tables are foundational to computer science and appear throughout modern software systems.

Frequently Asked Questions

Are Python dictionaries and hash tables the same thing?

Not exactly — a hash table is the general computer science concept, while Python's dict is a specific, highly optimized implementation of that concept, with added guarantees like insertion-order preservation that a generic hash table doesn't necessarily provide.

Why does Python raise a TypeError for unhashable types?

Because the correctness of a hash table depends entirely on a key's hash never changing while it's stored. Mutable types like lists could change after insertion, which would break lookups silently, so Python refuses to hash them at all rather than risk that.

Can I make a custom object usable as a dictionary key?

Yes — implement both __hash__() and __eq__() on your class. Objects are hashable by default using their identity, but if you override __eq__() without also defining __hash__(), Python makes the object unhashable automatically to prevent inconsistent behavior.

What happens when a hash table gets too full?

CPython automatically resizes the underlying table and rehashes all existing keys into the larger table once it crosses a certain load factor. This resize is an O(n) operation, but because it happens infrequently relative to the number of insertions, the amortized cost per insertion remains O(1).

Do two equal objects always have the same hash?

Yes, this is a strict requirement in Python: if a == b, then hash(a) == hash(b) must also be true. The reverse isn't required — two objects can have the same hash without being equal, which is exactly what a hash collision is.

Summary

Hash tables are the foundation of Python dictionaries and sets. By converting keys into numeric positions using a hash function, Python can store and retrieve values extremely efficiently, without needing to scan every item in the collection.

This design allows dictionary operations such as lookup, insertion, and deletion to run in close to constant time even when the dataset becomes very large — at the cost of requiring hashable, immutable keys and somewhat higher memory usage than simpler data structures.

Related Python Dictionary Tutorials




Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net