Hash tables (or hash maps) are one of the most fundamental data structures in computer science. In Python, the built-in dict
type provides a powerful and easy-to-use hash table implementation. Hash tables store data in key-value pairs and offer average-case constant time (O(1)) complexity for insertion, lookup, and deletion.
✅ Basic Hash Table Operations in Python
🔸 Insertion
python
# Creating a hash table
hash_table = {}
# Inserting key-value pairs
hash_table["apple"] = 5
hash_table["banana"] = 3
hash_table["orange"] = 7
🔍 Lookup
python
# Accessing values
print(hash_table["apple"]) # Output: 5
# Safe access using get (avoids KeyError)
print(hash_table.get("grape", "Not found")) # Output: Not found
❌ Deletion
python
# Deleting a key
del hash_table["banana"]
# Check if a key exists before deleting
if "orange" in hash_table:
del hash_table["orange"]
🔁 Iterating Over a Hash Table
python
for key, value in hash_table.items():
print(f"{key}: {value}")
⚙️ Use Cases
- Caching results (memoization)
- Counting frequencies
- Mapping keys to objects (e.g., user ID → user info)
- Lookup tables in algorithms
💡 Example: Word Frequency Counter
python
def count_words(text):
word_freq = {}
for word in text.split():
word = word.lower()
word_freq[word] = word_freq.get(word, 0) + 1
return word_freq
sentence = "apple banana apple orange banana apple"
print(count_words(sentence))
# Output: {'apple': 3, 'banana': 2, 'orange': 1}
📝 Summary
OperationDescriptionTime ComplexityInsertAdd a key-value pairO(1) averageLookupRetrieve a value for a given keyO(1) averageDeleteRemove a key-value pairO(1) average
Python dictionaries make hash table usage both simple and powerful. They're used extensively in algorithms, web development, and data processing.