Example

Example of using the hash table

Here’s an example of using a hash table in Python 3. Python dictionaries (dict) are implemented as hash tables, providing an efficient way to store and retrieve key-value pairs.

# Create a hash table (dictionary in Python)
hash_table = {}

# Insert key-value pairs
hash_table["apple"] = "A sweet red or green fruit"
hash_table["banana"] = "A long yellow fruit"
hash_table["orange"] = "A round citrus fruit"

# Retrieve values using keys
print("Apple:", hash_table["apple"])      # Output: Apple: A sweet red or green fruit
print("Banana:", hash_table["banana"])    # Output: Banana: A long yellow fruit
print("Orange:", hash_table["orange"])    # Output: Orange: A round citrus fruit

# Check if a key exists in the hash table
if "apple" in hash_table:
    print("Apple exists in the hash table.")

# Update a value
hash_table["banana"] = "A yellow fruit that's high in potassium"
print("Updated Banana:", hash_table["banana"])  # Output: Updated Banana: A yellow fruit that's high in potassium

# Delete a key-value pair
del hash_table["orange"]
print("Hash Table after deletion:", hash_table) # Output: Hash Table after deletion: {'apple': 'A sweet red or green fruit', 'banana': "A yellow fruit that's high in potassium"}

# Iterating through the hash table
for key, value in hash_table.items():
    print(f"{key}: {value}")

Explanation

  1. Insertion: We add key-value pairs to hash_table using the syntax hash_table[key] = value.
  2. Retrieval: Retrieve values by accessing hash_table[key].
  3. Check existence: Use the in keyword to check if a key exists in the hash table.
  4. Update: Reassign a value to an existing key to update it.
  5. Deletion: Use del to remove a key-value pair.