Hashing and hash tables in Python can be implemented using built-in features or custom solutions. Here's a comprehensive guide with practical examples:
Built-In Hashing Tools
1. hash() Function
Python's native hash() generates integer values for immutable objects:
print(hash("hello")) # -9161804372298436577 (varies between runs)
print(hash((1,2))) # 3713081631934410656
- Works for strings, numbers, and tuples[1][2]
- Inconsistent across Python sessions (security feature)[3]
- Fails for mutable types:
hash([1,2]) → TypeError[1][4]
2. Dictionaries (Built-in Hash Tables)
Python's dict uses hash tables internally:
# Create and use dictionary
data = {"name": "Alice", "age": 30}
print(data["name"]) # Alice (O(1) lookup)
- Keys must be hashable (immutable)[1][7]
- Automatic collision handling and resizing[7]
Custom Hash Table Implementation
Separate Chaining (Linked List Collision Resolution)
class HashTable:
def __init__(self, size=10):
self.size = size
self.table = [[] for _ in range(size)] # List of buckets
def _hash(self, key):
return hash(key) % self.size # Using Python's hash()
def insert(self, key, value):
bucket = self.table[self._hash(key)]
for i, (k, v) in enumerate(bucket):
if k == key: # Update existing
bucket[i] = (key, value)
return
bucket.append((key, value)) # New entry
def get(self, key):
bucket = self.table[self._hash(key)]
for k, v in bucket:
if k == key:
return v
raise KeyError(key)
Usage:
ht = HashTable()
ht.insert("apple", 5)
ht.insert("orange", 7)
print(ht.get("apple")) # 5
Open Addressing (Linear Probing)
class OpenHashTable:
def __init__(self, size=10):
self.size = size
self.keys = [None] * size
self.values = [None] * size
def _probe(self, key):
index = hash(key) % self.size
while self.keys[index] not in (None, key):
index = (index + 1) % self.size # Linear probing
return index
def insert(self, key, value):
index = self._probe(key)
self.keys[index] = key
self.values[index] = value
def get(self, key):
index = self._probe(key)
if self.keys[index] == key:
return self.values[index]
raise KeyError(key)