Introduction
There are numerous ways for storing and accessing data and one of the most popular methods is Hash Tables. Python has an in-built data type like a dictionary to implement hash tables. Here we are explaining how to implement hash tables and hashmaps in Python using dictionaries.
Hash tables and Hashmaps in Python
Hash tables and hashmaps are data structures used to map keys to their value pairs. It is used in functions for computing an index value that contains the elements to be inserted, removed, or searched. Hash tables are used to access data easily and faster. They store key-value pairs and the key will be generated using a hash function.
The built-in dictionary data type is used to implement a hash table or hashmap and the keys are created using a hash function. Dictionary data type contains the elements that can be ordered and changed. Consider the following example that explains how a dictionary can map employee names with their employee IDs.
Factor | Hash Table | Hashmap |
Type | Synchronized | Non-Synchronized |
Speed | Fast | Slow |
Null value | Allow one null key and two or more null values | Doesn’t allow any null keys or null values. |
Creating Dictionaries in Python
In Python, there are two ways to create a dictionary as follows
- Using curly braces – {}
- Using the dict() function
Curly Braces for Creating Dictionary
Following is the example that explains how curly braces are used to create dictionaries in Python
my_dict = {‘Grace’ : ‘001’, ‘Merlyn’ : ‘002’, ‘Jerry’: ‘003’}
print (my_dict)
type (my_dict)
Output
{‘Grace’ : ‘001’, ‘Merlyn’ : ‘002’, ‘Jerry’: ‘003’}
dict
The Dict() Function for Creating Dictionary
Following is the example that explain how dict() in-built function used for creating dictionaries in Python
new_dict = dict()
print (new_dict)
type (new_dict)
Output
{} dict
Here, an empty dictionary is created as no key_value pairs are given as a parameter to the dict() function. Follow the below method to add values to the dictionary
new_dict = dict{‘Grace’ : ‘001’, ‘Merlyn’ : ‘002’, ‘Jerry’: ‘003’}
print (new_dict)
type (new_dict)
Output
{‘Grace’ : ‘001’, ‘Merlyn’ : ‘002’, ‘Jerry’: ‘003’}
dict
Nested Dictionaries
If the dictionaries that are placed within other dictionaries are known as Nested Dictionaries.
Example
emp_details = {‘Employee’: {‘Grace’: { ‘ID’: ‘001’, ‘Salary’: 5000, ‘Position’: ‘Tech Lead’},
‘Merlyn’: {‘ID’ ‘002’, ‘Salary’: 8000, ‘Position’: ‘Project Manager’},
‘Jerry’: {‘ID’: ‘003’, ‘Salary’: 10000, ‘Position’: ‘General Manager’}}}
Operations with Hash Tables using Dictionaries
Following are the various operations that can be performed on hash tables in Python using dictionaries.
- Accessing Values
- Updating Values
- Deleting Element
Accessing Values
There are many ways to access the values of a dictionary and some of them are as follows
- Using key values
- Using functions
- Implementing the for loop
Key Values for accessing dictionary values
Key values implementation is used to access dictionary values.
Example
my_dict = {‘Grace’ : ‘001’, ‘Merlyn’ : ‘002’, ‘Jerry’: ‘003’}
my_dict[‘Grace’]
Output
‘001’
Functions for accessing dictionary values
Python has many in-built functions to be used for accessing dictionary values and some of them, get(), keys(), values(), and so on.
Example
my_dict = {‘Grace’ : ‘001’, ‘Merlyn’ : ‘002’, ‘Jerry’: ‘003’}
print(my_dict.keys())
print(my_dict.values())
print(my_dict.get(‘Grace’))
Output
dict_keys([‘Grace’, ‘Merlyn’, ‘Jerry’])
dict_keys([‘001’,’002’,’003’])
001
For loop for accessing the dictionary values
For loop in Python can be used to access the key-value pairs of dictionaries easily by iterating over them.
Example
my_dict = {‘Grace’ : ‘001’, ‘Merlyn’ : ‘002’, ‘Jerry’: ‘003’}
print(“All keys”)
for x in my_dict:
print(x)
print(“All values”)
for x in my_dict.values():
print(x)
print(“All keys and values”
for x, y in my_dict.items()
print (x, “:”, y)
Output
All keys
Grace
Merlyn
Jerry
All values
001
002
003
All keys and values
Grace: 001
Merlyn: 002
Jerry: 003
Updating values in Dictionaries
We can modify the dictionary as per the requirement as it is a mutable data type. If we want to update the ID of the employee named grace from ‘001’ to ‘007’ or if we want to add up the employee, they are possible in Python.
Example
my_dict = {‘Grace’ : ‘001’, ‘Merlyn’ : ‘002’, ‘Jerry’: ‘003’}
my_dict[‘Grace] = ‘007’ #updating the value of Grace
my_dict[‘Freddy’] = ‘004’ #adding the new key-value pair
print(my_dict)
Output
{‘Grace’: ‘007’, ‘Merlyn’ : ‘002’, ‘Jerry’: ‘003’, ‘Freddy’: ‘004’}
Deleting key-pair values from a dictionary
Python has some popular functions used to remove items from a dictionary and they are del(), pop(), popitem(), clear(), and so on.
Example
my_dict = {‘Grace’ : ‘007’, ‘Merlyn’ : ‘002’, ‘Jerry’: ‘003’, ‘Freddy’: ‘004’}
del my_dict[‘Grace’] #removes key-value of Grace
my_dict.pop(‘Merlyn’) #removes the value of Merlyn
my_dict.popitem() #removes the last added item
print(my_dict)
Output
{‘Jerry’: ‘003’}
Converting Dictionary into a dataframe
It is possible to convert the dictionary items into a dataframe in Python programming language using the pandas library. Check out the following example that explains how to convert them into a dataframe.
Example
import pandas as pan
emp_details = {‘Employee’: {‘Grace’: { ‘ID’: ‘001’, ‘Salary’: 5000, ‘Position’: ‘Tech Lead’},
‘Merlyn’: {‘ID’ ‘002’, ‘Salary’: 8000, ‘Position’: ‘Project Manager’},
‘Jerry’: {‘ID’: ‘003’, ‘Salary’: 10000, ‘Position’: ‘General Manager’}}}
df=pd.DataFrame(emp_details[‘Employee’])
print(df)
Employee | Grace | Merlyn | Jerry |
Designation | Tech Lead | Project Manager | General Manager |
ID | 001 | 002 | 003 |
Salary | 5000 | 8000 | 10000 |
Conclusion
We hope this blog helps you understand about Hash Tables and Hash Maps in Python. Learn the best Python Course at SLA to obtain complete hands-on exposure on python concepts. Become a master in application development, data science process, or scrip writing by enrolling in our Python Training in Chennai.