Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Science USbreadcumb forward arrow iconHash tables and Hash maps in Python

Hash tables and Hash maps in Python

Last updated:
5th Nov, 2022
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
Hash tables and Hash maps in Python

Data requires multiple ways to be accessed or stored. Hash Tables and Hashmaps happen to be the best data structures to implement this in Python via the built-in data type known as a dictionary. 

A Hashmap or a Hash table in data structure maps keys to its value pairs and uses a function that computes any index value holding the elements to be inserted, searched, or removed. This helps make data access easier and faster. Hash tables generally store key-value pairs and use the hash function for generating a key.

In this article, you will learn what Hash Tables and Hashmaps are and how they are implemented in Python.

Learn data science to gain edge over your competitors

Ads of upGrad blog

What is a Hash table or a Hashmap Python?

A hash table or hashmap Python is an indexed data structure. It uses hash functions to compute an index by using a key into an array of slots or buckets. You can map its value to a bucket using the corresponding index, and the key is immutable and unique. 

Hashmaps are similar to a cabinet of drawers labeled with the things they store. For instance, hashmaps can store user information like the first and last name, etc., in the bucket.  

The hash function is integral for the implementation of a hashmap. It uses the key and translates it to the bucket’s index in the bucket list. Ideal hashing produces a separate index for every key. However, keep in mind that collisions can occur. When hashing produces an already existing index, a bucket for multiple values can be easily used by rehashing or appending a list. In Python, an example of hash maps is dictionaries. 

Let us look into the hashmap implementation in detail to learn how to customize and build data structures for search optimization.

Hashmap in Python

The hashmap includes the following functions:

  • set_val(key, value): This function is used for inserting a key-value pair into the hash map. If there is already an existing value in the hash map, you must update the value.
  • get_val(key): This function returns the value to the specified key that is mapped or “No record found” if this map has no mapping for the key.
  • delete_val(key): Deletes the mapping for the particular key if the hashmap has the mapping for the key.

Implementation:-

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(upGrad@example.com’, ‘some value’)

print(hash_table)

print()

hash_table.set_val(‘portal@example.com’, ‘some other value’)

print(hash_table)

print()

# search/access a record with key

print(hash_table.get_val(‘portal@example.com’))

print()

# delete or remove a value

hash_table.delete_val(‘portal@example.com’)

print(hash_table)

 

Output:-

[][][][][][][][][][][][][][][][][][][][][] (upGrad@example.com’, ‘some value’) ][][][][][][][][][][][][][][][][][][][][][][][][][][]

[][][][][][][][][][][][][][][][][][][][][] (upGrad@example.com’, ‘some value’) ][][][][][][(‘portal@example.com’, ‘some other value’)][][][][][][][][][][][][][][][][][][][][][]

Some other value

[][][][][][][][][][][][][][][][][][][][][] (upGrad@example.com’, ‘some value’) ][][][][][][][][][][][][][][][][][][][][][][][][][][]

Check our US - Data Science Programs

Performing Operations on Hash tables using Dictionaries:

There are numerous operations that can be performed in Python on hash tables via dictionaries. They are as follows:-

  • Accessing Values
  • Updating Values
  • Deleting Element

Accessing Values:

You can easily access the values of a dictionary in the following ways:-

  • Using key values
  • Using functions
  • Implementing the for loop

Using key values:

You can access dictionary values using the key values like below:-

my_dict={‘Elsa’ : ‘001’ , ‘Anna’: ‘002’ , ‘Olaf’: ‘003’}

my_dict[‘Anna’]

Output: ‘002′

Using functions:

There are numerous built-in functions such as get(), keys(), values(), etc.

my_dict={‘Elsa’ : ‘001’ , ‘Anna’: ‘002’ , ‘Olaf’: ‘003’}

print(my_dict.keys())

print(my_dict.values())

print(my_dict.get(‘Elsa’))

Output:-

dict_keys([‘Elsa’, ‘Anna’, ‘Olaf’])

dict_values([‘001’, ‘002’, ‘003’])

001

Implementing the for loop:

The loop gives you access to the the key-value pairs of a dictionary by iterating over them. For example:

my_dict={‘Elsa’ : ‘001’ , ‘Anna’: ‘002’ , ‘Olaf’: ‘003’}

print(“All keys”)

for x in my_dict:

    print(x)   #prints the keys

print(“All values”)

for x in my_dict.values():

    print(x)   #prints values

print(“All keys and values”)

for x,y in my_dict.items():

    print(x, “:” , y)   #prints keys and values

Output:

All keys

Elsa

Anna

Olaf

All values

001

002

003

All keys and values

Elsa: 001

Anna : 002

Olaf: 003

Updating Values:

Dictionaries are mutable data types that can be updated when required. You can do as follows:-

my_dict={‘Elsa’ : ‘001’ , ‘Anna’: ‘002’ , ‘Olaf’: ‘003’}

my_dict[‘Olaf’] = ‘004’   #Updating the value of Dave

my_dict[‘Kristoff’] = ‘005’  #adding a key-value pair

print(my_dict)

Output: {‘Elsa’: ‘001’ , ‘Anna’: ‘002’ , ‘Olaf’: ‘004’, ‘Kristoff’: ‘005’}

Deleting items from a dictionary:

You can delete items from a dictionary with functions like del(), pop(), popitem(), clear(), etc. For example:

my_dict={‘Elsa’ : ‘001’ , ‘Anna’: ‘002’ , ‘Olaf’: ‘003’}

del my_dict[‘Elsa’]  #removes key-value pair of ‘Elsa’

my_dict.pop(‘Anna’)   #removes the value of ‘Anna’

my_dict.popitem() #removes the last inserted item

print(my_dict)

Output: {‘Olaf’: ‘003’}

Conclusion

We can easily conclude that hashmaps and hash table Python are integral for easier and faster access to relevant data. It is a valuable tool for data science professionals like data scientists and data analysts. If you are interested in learning more about the field of Data Science, upGrad has the best Professional Certificate Program in Data Science for Business Decision Making

Ads of upGrad blog

Check Out upGrad’s Advanced Certificate Programme in DevOps

 

 

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.
Get Free Consultation

Selectcaret down icon
Select Area of interestcaret down icon
Select Work Experiencecaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Data Science Courses

Frequently Asked Questions (FAQs)

1What is a hashmap, Python, and hash table, Python?

A hashtable helps in storing key-value pairs where a key is generated using a hash function. Hashmaps or hashtable implementations in Python are done with built-in dictionaries.

2What is the difference between a hashmap and a hash table Python?

A Hashmap is unsynchronized, but a Hashtable is synchronized. This means, that Hash tables are thread-safe and can be shared amongst numerous threads, but HashMap needs proper synchronization before being shared.

3Is map a Hashtable?

A hash table Python also called a hash map, is a data structure mapping keys to values. It uses the hashing technique.

Explore Free Courses

Suggested Blogs

Most Asked Python Interview Questions & Answers
5578
Python is considered one of the easiest programming languages. It is widely used for web development, gaming applications, data analytics and visualiz
Read More

by Pavan Vadapalli

14 Jul 2024

Top 10 Real-Time SQL Project Ideas: For Beginners & Advanced
15656
Thanks to the big data revolution, the modern business world collects and analyzes millions of bytes of data every day. However, regardless of the bus
Read More

by Pavan Vadapalli

28 Aug 2023

Python Free Online Course with Certification [US 2024]
5519
Data Science is now considered to be the future of technology. With its rapid emergence and innovation, the career prospects of this course are increa
Read More

by Pavan Vadapalli

14 Apr 2023

13 Exciting Data Science Project Ideas & Topics for Beginners in US [2024]
5474
Data Science projects are great for practicing and inheriting new data analysis skills to stay ahead of the competition and gain valuable experience.
Read More

by Rohit Sharma

07 Apr 2023

4 Types of Data: Nominal, Ordinal, Discrete, Continuous
6528
Data refers to the collection of information that is gathered and translated for specific purposes. With over 2.5 quintillion data being produced ever
Read More

by Rohit Sharma

06 Apr 2023

Best Python Free Online Course with Certification You Should Check Out [2024]
5755
Data Science is now considered to be the future of technology. With its rapid emergence and innovation, the career prospects of this course are increa
Read More

by Rohit Sharma

05 Apr 2023

5 Types of Binary Tree in Data Structure Explained
5385
A binary tree is a non-linear tree data structure that contains each node with a maximum of 2 children. The binary name suggests the number 2, so any
Read More

by Rohit Sharma

03 Apr 2023

42 Exciting Python Project Ideas & Topics for Beginners [2024]
6037
Python is an interpreted, high-level, object-oriented programming language and is prominently ranked as one of the top 5 most famous programming langu
Read More

by Rohit Sharma

02 Apr 2023

5 Reasons Why Python Continues To Be The Top Programming Language
5365
Introduction Python is an all-purpose high-end scripting language for programmers, which is easy to understand and replicate. It has a massive base o
Read More

by Rohit Sharma

01 Apr 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon