Hash maps are indexed data structures. A hash map makes use of a hash function to compute an index with a key into an array of buckets or slots. Its value is mapped to the bucket with the corresponding index. The key is unique and immutable. Think of a hash map as a cabinet having drawers with labels for the things stored in them. For example, storing user information- consider email as the key, and we can map values corresponding to that user such as the first name, last name etc to a bucket.
Hash function is the core of implementing a hash map. It takes in the key and translates it to the index of a bucket in the bucket list. Ideal hashing should produce a different index for each key. However, collisions can occur. When hashing gives an existing index, we can simply use a bucket for multiple values by appending a list or by rehashing.
In Python, dictionaries are examples of hash maps. We’ll see the implementation of hash map from scratch in order to learn how to build and customize such data structures for optimizing search.
The hash map design will include the following functions:
- set_val(key, value): Inserts a key-value pair into the hash map. If the value already exists in the hash map, update the value.
- get_val(key): Returns the value to which the specified key is mapped, or “No record found” if this map contains no mapping for the key.
- delete_val(key): Removes the mapping for the specific key if the hash map contains the mapping for the key.
Below is the implementation.
Python
class HashTable:
# Create empty bucket list of given size
def __init__(self, size):
self.size = size
self.hash_table = self.create_buckets()
def create_buckets(self):
return [[] for _ in range(self.size)]
# Insert values into hash map
def set_val(self, key, val):
# Get the index from the key
# using hash function
hashed_key = hash(key) % self.size
# Get the bucket corresponding to index
bucket = self.hash_table[hashed_key]
found_key = False
for index, record in enumerate(bucket):
record_key, record_val = record
# check if the bucket has same key as
# the key to be inserted
if record_key == key:
found_key = True
break
# If the bucket has same key as the key to be inserted,
# Update the key value
# Otherwise append the new key-value pair to the bucket
if found_key:
bucket[index] = (key, val)
else:
bucket.append((key, val))
# Return searched value with specific key
def get_val(self, key):
# Get the index from the key using
# hash function
hashed_key = hash(key) % self.size
# Get the bucket corresponding to index
bucket = self.hash_table[hashed_key]
found_key = False
for index, record in enumerate(bucket):
record_key, record_val = record
# check if the bucket has same key as
# the key being searched
if record_key == key:
found_key = True
break
# If the bucket has same key as the key being searched,
# Return the value found
# Otherwise indicate there was no record found
if found_key:
return record_val
else:
return "No record found"
# Remove a value with specific key
def delete_val(self, key):
# Get the index from the key using
# hash function
hashed_key = hash(key) % self.size
# Get the bucket corresponding to index
bucket = self.hash_table[hashed_key]
found_key = False
for index, record in enumerate(bucket):
record_key, record_val = record
# check if the bucket has same key as
# the key to be deleted
if record_key == key:
found_key = True
break
if found_key:
bucket.pop(index)
return
# To print the items of hash map
def __str__(self):
return "".join(str(item) for item in self.hash_table)
hash_table = HashTable(50)
# insert some values
hash_table.set_val('[email protected]', 'some value')
print(hash_table)
print()
hash_table.set_val('[email protected]', 'some other value')
print(hash_table)
print()
# search/access a record with key
print(hash_table.get_val('[email protected]'))
print()
# delete or remove a value
hash_table.delete_val('[email protected]')
print(hash_table)
Output:

Time Complexity:
Memory index access takes constant time and hashing takes constant time. Hence, the search complexity of a hash map is also constant time, that is, O(1).
Advantages of HashMaps
● Fast random memory access through hash functions
● Can use negative and non-integral values to access the values.
● Keys can be stored in sorted order hence can iterate over the maps easily.
Disadvantages of HashMaps
● Collisions can cause large penalties and can blow up the time complexity to linear.
● When the number of keys is large, a single hash function often causes collisions.
Applications of HashMaps
● These have applications in implementations of Cache where memory locations are mapped to small sets.
● They are used to index tuples in Database management systems.
● They are also used in algorithms like the Rabin Karp pattern matching
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
10 min read
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
13 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. How do
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Conditions to apply Binary Search Algorithm in a Data S
15+ min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read