Python Hash Tables


A hash table is a powerful data structure that gives you very fast access to data. Instead of searching through a list or linked list one element at a time, a hash table lets you store a value at a specific position using a hash function. This allows average constant-time performance for inserting, searching and deleting. Hash tables are used in databases, caching, dictionaries, compilers and almost every real-world application where quick lookup is important.

In this tutorial, you will learn how hash tables work, how hashing converts keys into positions, how collisions occur, how Python’s dictionary uses hashing internally and how you can build your own hash table using lists. You will also explore common operations and practical examples so you can apply hashing concepts in your DSA journey.

What Is a Hash Table?

A hash table is a structure that stores data using key-value pairs. Each key is passed through a hash function, which generates an index. The value is stored at that index.

This makes access very fast because you don’t need to scan through the entire structure.

Example:

Key → Hash Function → Index → Value Stored

If you search for the same key, the hash function returns the same index, and you get the value immediately.

What Is Hashing?

Hashing is the process of converting a key into a fixed index using a mathematical function. This index is used to store or retrieve the value.

A hash function should be:

  • Fast

  • Reliable

  • Uniform

Uniform means it spreads keys across the table without clustering too many items in the same area.

What is Keys and Values?

A hash table stores its data as pairs:

"name": "Riya"
"age": 22
"city": "Delhi"

The key is hashed, and its value is placed in the table. Keys must be unique, while values can be anything.

Collisions in Hash Tables

A collision happens when two different keys generate the same index. Collisions are normal and expected, but you need a strategy to handle them.

Two common ways to handle collisions:

Chaining

Store multiple values at the same index using a list or linked list.

Index 3 → [("age", 22), ("salary", 50000)]

Open Addressing

If one index is taken, move to the next empty index.

Both methods allow hash tables to work efficiently even with collisions.

Python Dictionary and Hash Tables

In Python, the built-in dictionary is implemented using a hash table. When you write:

data = {"name": "Nia", "age": 25}

Python internally hashes each key and places the value in the table. This is why dictionary operations like searching for a key are extremely fast.

Creating a Simple Hash Function

Here is an example of a basic hash function:

def simple_hash(key):
    return sum(ord(char) for char in key) % 10

This converts characters into ASCII values and takes the remainder. The result is an index between 0 and 9.

While this is not a strong function, it is useful for learning.

Building Your Own Hash Table Class

Here is a simple implementation using lists and chaining:

class HashTable:
    def __init__(self):
        self.size = 10
        self.table = [[] for _ in range(self.size)]

    def hash(self, key):
        return sum(ord(c) for c in key) % self.size

    def insert(self, key, value):
        index = self.hash(key)
        for pair in self.table[index]:
            if pair[0] == key:
                pair[1] = value
                return
        self.table[index].append([key, value])

    def get(self, key):
        index = self.hash(key)
        for pair in self.table[index]:
            if pair[0] == key:
                return pair[1]
        return None

    def delete(self, key):
        index = self.hash(key)
        for i, pair in enumerate(self.table[index]):
            if pair[0] == key:
                del self.table[index][i]
                return

This class stores items using lists and handles collisions using chaining.

Inserting Data in a Hash Table

ht = HashTable()
ht.insert("name", "Aisha")
ht.insert("city", "Mumbai")

The keys are hashed and placed in their respective lists.

Retrieving Data

ht.get("city")

This returns the stored value instantly if the key exists.

Deleting Data

ht.delete("name")

The class removes the key-value pair after locating it.

Real-Life Uses of Hash Tables

Databases

Indexes use hashing for quick record lookup.

Caching

Web browsers and servers cache data using hash maps.

Password Storage

Hashed passwords are stored securely.

File Systems

Hashing helps identify duplicate files.

Compilers

Symbol tables use hash maps to manage variables and functions.

These examples show how important hash tables are in software systems.

Hash Table Simulation: Student Records

students = HashTable()
students.insert("roll_101", "Aditi")
students.insert("roll_102", "Meera")

print(students.get("roll_101"))

Fast lookup helps when managing large databases.

Hash Table Simulation: Caching Example

cache = HashTable()
cache.insert("page_home", "<html>Home Page</html>")
cache.insert("page_about", "<html>About Page</html>")

print(cache.get("page_home"))

Caching avoids loading the same data again and again.

Practical Examples

Example 1: Create a hash table

ht = HashTable()

Example 2: Insert key-value pair

ht.insert("fruit", "apple")

Example 3: Retrieve value

ht.get("fruit")

Example 4: Update existing key

ht.insert("fruit", "orange")

Example 5: Delete a key

ht.delete("fruit")

Example 6: Check missing key

ht.get("unknown")

Example 7: Collision test

ht.insert("ab", 10)
ht.insert("ba", 20)

Example 8: Iterating stored data

for i in ht.table:
    print(i)

Example 9: Using dictionary as hash table

d = {"age": 30}

Example 10: Searching a key in dictionary

"age" in d

Summary of the Tutorial

A hash table stores data using keys and indexes generated by a hash function. You learned how hashing works, why collisions occur and how chaining and open addressing help solve them. You also saw how Python dictionaries use hashing internally and how to build a custom hash table class. Hash tables are used in databases, caching, compilers, file systems and almost every area where fast lookup is required. With this knowledge, you can move confidently into more advanced DSA structures like graphs, binary trees and search algorithms.


Practice Questions

Q1. Write a Python program to create a dictionary of employee ID → name.

Q2. Write a Python program to add a new employee to the dictionary.

Q3. Write a Python program to update the name of an existing employee.

Q4. Write a Python program to delete an employee using del keyword.

Q5. Write a Python program to check if the key "105" exists in the dictionary.

Q6. Write a Python program to use a loop to print all keys and values in the dictionary.

Q7. Write a Python program to get the value for key "104" using .get().

Q8. Write a Python program to list all keys using the .keys() method.

Q9. Write a Python program to remove an item from the dictionary using .pop().

Q10. Write a Python program to count the number of items in the dictionary using len().


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top