Implementation of Hash Table in Python using Separate Chaining
Last Updated :
23 Jul, 2025
A hash table is a data structure that allows for quick insertion, deletion, and retrieval of data. It works by using a hash function to map a key to an index in an array. In this article, we will implement a hash table in Python using separate chaining to handle collisions.
Components of hashing
Separate chaining is a technique used to handle collisions in a hash table. When two or more keys map to the same index in the array, we store them in a linked list at that index. This allows us to store multiple values at the same index and still be able to retrieve them using their key.
Way to implement Hash Table using Separate Chaining
Way to implement Hash Table using Separate Chaining:
Create two classes: 'Node' and 'HashTable'.
The 'Node' class will represent a node in a linked list. Each node will contain a key-value pair, as well as a pointer to the next node in the list.
Python3
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
The 'HashTable' class will contain the array that will hold the linked lists, as well as methods to insert, retrieve, and delete data from the hash table.
Python3
class HashTable:
def __init__(self, capacity):
self.capacity = capacity
self.size = 0
self.table = [None] * capacity
The '__init__' method initializes the hash table with a given capacity. It sets the 'capacity' and 'size' variables and initializes the array to 'None'.
The next method is the '_hash' method. This method takes a key and returns an index in the array where the key-value pair should be stored. We will use Python's built-in hash function to hash the key and then use the modulo operator to get an index in the array.
Python3
def _hash(self, key):
return hash(key) % self.capacity
The 'insert' method will insert a key-value pair into the hash table. It takes the index where the pair should be stored using the '_hash' method. If there is no linked list at that index, it creates a new node with the key-value pair and sets it as the head of the list. If there is a linked list at that index, iterate through the list till the last node is found or the key already exists, and update the value if the key already exists. If it finds the key, it updates the value. If it doesn't find the key, it creates a new node and adds it to the head of the list.
Python3
def insert(self, key, value):
index = self._hash(key)
if self.table[index] is None:
self.table[index] = Node(key, value)
self.size += 1
else:
current = self.table[index]
while current:
if current.key == key:
current.value = value
return
current = current.next
new_node = Node(key, value)
new_node.next = self.table[index]
self.table[index] = new_node
self.size += 1
The search method retrieves the value associated with a given key. It first gets the index where the key-value pair should be stored using the _hash method. It then searches the linked list at that index for the key. If it finds the key, it returns the associated value. If it doesn't find the key, it raises a KeyError.
Python3
def search(self, key):
index = self._hash(key)
current = self.table[index]
while current:
if current.key == key:
return current.value
current = current.next
raise KeyError(key)
The 'remove' method removes a key-value pair from the hash table. It first gets the index where the pair should be stored using the `_hash` method. It then searches the linked list at that index for the key. If it finds the key, it removes the node from the list. If it doesn't find the key, it raises a `KeyError`.
Python3
def remove(self, key):
index = self._hash(key)
previous = None
current = self.table[index]
while current:
if current.key == key:
if previous:
previous.next = current.next
else:
self.table[index] = current.next
self.size -= 1
return
previous = current
current = current.next
raise KeyError(key)
'__str__' method that returns a string representation of the hash table.
Python3
def __str__(self):
elements = []
for i in range(self.capacity):
current = self.table[i]
while current:
elements.append((current.key, current.value))
current = current.next
return str(elements)
Here's the complete implementation of the 'HashTable' class:
Python3
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
class HashTable:
def __init__(self, capacity):
self.capacity = capacity
self.size = 0
self.table = [None] * capacity
def _hash(self, key):
return hash(key) % self.capacity
def insert(self, key, value):
index = self._hash(key)
if self.table[index] is None:
self.table[index] = Node(key, value)
self.size += 1
else:
current = self.table[index]
while current:
if current.key == key:
current.value = value
return
current = current.next
new_node = Node(key, value)
new_node.next = self.table[index]
self.table[index] = new_node
self.size += 1
def search(self, key):
index = self._hash(key)
current = self.table[index]
while current:
if current.key == key:
return current.value
current = current.next
raise KeyError(key)
def remove(self, key):
index = self._hash(key)
previous = None
current = self.table[index]
while current:
if current.key == key:
if previous:
previous.next = current.next
else:
self.table[index] = current.next
self.size -= 1
return
previous = current
current = current.next
raise KeyError(key)
def __len__(self):
return self.size
def __contains__(self, key):
try:
self.search(key)
return True
except KeyError:
return False
# Driver code
if __name__ == '__main__':
# Create a hash table with
# a capacity of 5
ht = HashTable(5)
# Add some key-value pairs
# to the hash table
ht.insert("apple", 3)
ht.insert("banana", 2)
ht.insert("cherry", 5)
# Check if the hash table
# contains a key
print("apple" in ht) # True
print("durian" in ht) # False
# Get the value for a key
print(ht.search("banana")) # 2
# Update the value for a key
ht.insert("banana", 4)
print(ht.search("banana")) # 4
ht.remove("apple")
# Check the size of the hash table
print(len(ht)) # 3
Time Complexity and Space Complexity:
- The time complexity of the insert, search and remove methods in a hash table using separate chaining depends on the size of the hash table, the number of key-value pairs in the hash table, and the length of the linked list at each index.
- Assuming a good hash function and a uniform distribution of keys, the expected time complexity of these methods is O(1) for each operation. However, in the worst case, the time complexity can be O(n), where n is the number of key-value pairs in the hash table.
- However, it is important to choose a good hash function and an appropriate size for the hash table to minimize the likelihood of collisions and ensure good performance.
- The space complexity of a hash table using separate chaining depends on the size of the hash table and the number of key-value pairs stored in the hash table.
- The hash table itself takes O(m) space, where m is the capacity of the hash table. Each linked list node takes O(1) space, and there can be at most n nodes in the linked lists, where n is the number of key-value pairs stored in the hash table.
- Therefore, the total space complexity is O(m + n).
Conclusion:
In practice, it is important to choose an appropriate capacity for the hash table to balance the space usage and the likelihood of collisions. If the capacity is too small, the likelihood of collisions increases, which can cause performance degradation. On the other hand, if the capacity is too large, the hash table can consume more memory than necessary.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem