Ejercicio
Tabla Hash: Implementación De Un Diccionario
Objectivo
Desarrollar un programa Python que implemente una tabla hash utilizando un diccionario. El programa debe permitir insertar pares clave-valor, recuperar valores por claves y eliminar pares clave-valor. Implementar un manejo básico de errores para los casos en los que no se encuentra una clave. Utilizar el diccionario integrado de Python para simular el comportamiento de una tabla hash, demostrando una recuperación y modificación de datos eficiente.
Ejemplo de ejercicio de Python
Mostrar código Python
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.
Código de ejemplo copiado
Comparte este ejercicio de Python