Open In App

Deletion in Hash Tables using Python

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Hash tables are fundamental data structures used in computer science for efficient data storage and retrieval. They provide constant-time average-case complexity for basic operations like insertion, deletion, and search. Deletion in hash tables involves removing an element from the table based on its key. Python offers built-in support for hash tables through dictionaries, which are implemented using hash tables.

In this article, we’ll explore the process of deletion in hash tables using Python. We’ll cover the underlying concepts, provide practical examples with proper output screenshots, and outline the steps needed to perform deletion effectively.

Approach to Deletion in Hash Tables

  1. Hash the Key: Calculate the hash value of the key to determine the index where the key-value pair is stored.
  2. Search for the Key: Traverse the list at the hashed index to find the key-value pair with the given key.
  3. Delete the Key-Value Pair: Once the key is found, remove the key-value pair from the list.

Steps to Implement Deletion in Hash Table in Python

  1. Identify the key you want to delete.
  2. Check if the key exists in the hash table.
  3. If the key exists, use the del keyword to remove the key-value pair from the hash table.
  4. Optionally, handle collision resolution if necessary.
  5. Verify the deletion by inspecting the updated hash table.

Below is the implementation of the approach:

Python
# Creating a hash table
hash_table = {'A': 1, 'B': 2, 'C': 3, 'D': 4}

# Deleting an element from the hash table
delete_key = 'B'
if delete_key in hash_table:
    del hash_table[delete_key]
    print("Key '{}' deleted successfully.".format(delete_key))
else:
    print("Key '{}' not found in the hash table.".format(delete_key))

# Displaying the updated hash table
print("Updated hash table:", hash_table)

Output
Key 'B' deleted successfully.
('Updated hash table:', {'A': 1, 'C': 3, 'D': 4})

In this example, we create a hash table ‘hash_table’ with four key-value pairs. We then delete the key ‘B’ from the hash table using the ‘del’ keyword. Finally, we print the updated hash table to verify the deletion.

Time Complexity: O(1) on average
Auxiliary Space Complexity: O(n)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads