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
Show 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