Python Hash Tables


Hash Table is a data structure that stores data in key-value pairs. In Python, the built-in dict (dictionary) is the most common way to implement a hash table.

Hash tables use a hash function to map keys to a specific index where the value is stored.


🔹 Creating a Hash Table in Python

# Create a hash table (dictionary)
students = {
    "101": "Alice",
    "102": "Bob",
    "103": "Charlie"
}

print(students["102"])  # Output: Bob

✅ Keys can be strings, numbers, or tuples
✅ Values can be of any data type


🔹 Adding Items

students["104"] = "David"

🔹 Updating Values

students["103"] = "Eve"

🔹 Deleting Items

del students["101"]

🔹 Looping Through a Hash Table

for key, value in students.items():
    print(key, ":", value)

🔹 Useful Dictionary Methods

Method Description
dict.get(key) Returns value for key (or None)
dict.keys() Returns all keys
dict.values() Returns all values
dict.items() Returns all key-value pairs
dict.pop(key) Removes item by key
key in dict Checks if key exists

🔹 Hashing Example (Behind the Scenes)

print(hash("apple"))  # Outputs an integer (hash value)

Python internally uses this hash value to store keys efficiently.


🔹 Use Cases of Hash Tables

  • Storing user profiles

  • Phonebooks

  • Caching

  • Counting items (frequency maps)

  • Lookup tables


Practice Questions

Q1. Write a Python program to create a dictionary of employee ID → name.

Q2. Write a Python program to add a new employee to the dictionary.

Q3. Write a Python program to update the name of an existing employee.

Q4. Write a Python program to delete an employee using del keyword.

Q5. Write a Python program to check if the key "105" exists in the dictionary.

Q6. Write a Python program to use a loop to print all keys and values in the dictionary.

Q7. Write a Python program to get the value for key "104" using .get().

Q8. Write a Python program to list all keys using the .keys() method.

Q9. Write a Python program to remove an item from the dictionary using .pop().

Q10. Write a Python program to count the number of items in the dictionary using len().


Go Back Top