Hash Table - Implementing a Dictionary - Python Programming Exercise

In this exercise, you will develop a Python program that implements a hash table using a dictionary. This exercise is perfect for practicing data structures, dictionary operations, and error handling in Python. By implementing this program, you will gain hands-on experience in handling data structures, dictionary operations, and error handling in Python. This exercise not only reinforces your understanding of data structures but also helps you develop efficient coding practices for managing user interactions.

 Category

Memory Management Techniques

 Exercise

Hash Table - Implementing A Dictionary

 Objective

Develop a Python program that implements a hash table using a dictionary. The program should allow inserting key-value pairs, retrieving values by keys, and deleting key-value pairs. Implement basic error handling for cases where a key is not found. Use Python's built-in dictionary to simulate the behavior of a hash table, demonstrating efficient data retrieval and modification.

 Example Python Exercise

 Copy Python Code
class HashTable:
    def __init__(self):
        """Initialize the hash table (using a dictionary)."""
        self.table = {}

    def insert(self, key, value):
        """Insert a key-value pair into the hash table."""
        self.table[key] = value
        print(f"Inserted: {key} -> {value}")

    def retrieve(self, key):
        """Retrieve the value associated with the key from the hash table."""
        try:
            value = self.table[key]
            print(f"Retrieved: {key} -> {value}")
            return value
        except KeyError:
            print(f"Error: Key '{key}' not found.")
            return None

    def delete(self, key):
        """Delete the key-value pair from the hash table."""
        try:
            del self.table[key]
            print(f"Deleted: {key}")
        except KeyError:
            print(f"Error: Key '{key}' not found.")

    def display(self):
        """Display all key-value pairs in the hash table."""
        if self.table:
            print("Hash Table Contents:")
            for key, value in self.table.items():
                print(f"{key}: {value}")
        else:
            print("The hash table is empty.")

def main():
    """Main function to demonstrate the hash table operations."""
    hash_table = HashTable()

    while True:
        print("\nChoose an operation:")
        print("1. Insert a key-value pair")
        print("2. Retrieve a value by key")
        print("3. Delete a key-value pair")
        print("4. Display the hash table")
        print("5. Exit")

        choice = input("Enter your choice (1-5): ").strip()

        if choice == '1':
            key = input("Enter the key: ").strip()
            value = input("Enter the value: ").strip()
            hash_table.insert(key, value)
        elif choice == '2':
            key = input("Enter the key: ").strip()
            hash_table.retrieve(key)
        elif choice == '3':
            key = input("Enter the key to delete: ").strip()
            hash_table.delete(key)
        elif choice == '4':
            hash_table.display()
        elif choice == '5':
            print("Exiting program.")
            break
        else:
            print("Invalid choice, please select a valid option.")

# Run the program
if __name__ == "__main__":
    main()

 Output

Choose an operation:
1. Insert a key-value pair
2. Retrieve a value by key
3. Delete a key-value pair
4. Display the hash table
5. Exit
Enter your choice (1-5): 1
Enter the key: name
Enter the value: Alice
Inserted: name -> Alice

Choose an operation:
1. Insert a key-value pair
2. Retrieve a value by key
3. Delete a key-value pair
4. Display the hash table
5. Exit
Enter your choice (1-5): 2
Enter the key: name
Retrieved: name -> Alice

Choose an operation:
1. Insert a key-value pair
2. Retrieve a value by key
3. Delete a key-value pair
4. Display the hash table
5. Exit
Enter your choice (1-5): 3
Enter the key to delete: name
Deleted: name

Choose an operation:
1. Insert a key-value pair
2. Retrieve a value by key
3. Delete a key-value pair
4. Display the hash table
5. Exit
Enter your choice (1-5): 2
Enter the key: name
Error: Key 'name' not found.

 Share this Python Exercise

 More Python Programming Exercises of Memory Management Techniques

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Parenthesis Matching

    In this exercise, you will develop a Python program that checks if parentheses in a given expression are properly balanced. This exercise is perfect for practi...

  •  Merging and Sorting Files

    In this exercise, you will develop a Python program that merges the contents of multiple text files into a single file and sorts the content alphabetically or numeric...

  •  ArrayList: Storing Points

    In this exercise, you will develop a Python program that uses an ArrayList-like structure (a list) to store a collection of points, where each point is represented by...

  •  File Search Operations

    In this exercise, you will develop a Python program that searches for a specific word or phrase within a text file. This exercise is perfect for practicing fil...

  •  Implementing a Queue Using List

    In this exercise, you will develop a Python program to implement a queue using a list. This exercise is perfect for practicing data structures, list manipulati...

  •  Building a Stack Using Lists

    In this exercise, you will develop a Python program to implement a stack using a list. This exercise is perfect for practicing data structures, list manipulati...