Python dictionaries use a hash table internally, where keys are stored based on their hash values. A hash collision occurs when two different keys generate the same hash value. To handle this, Python uses open addressing with probing.
A Python dictionary consists of:
Python uses open addressing with probing to resolve collisions. This means:
d = {}
d[1] = "One"
d[2] = "Two"
# Assume hash(1) and hash(2) collide
# Python finds an empty slot for the second key
Even if two keys collide, they still get stored separately due to probing.
hash(key) % table_size
→ Finds the initial slot.(key, value)
.class SimpleDict:
def __init__(self, size=5):
self.size = size
self.table = [None] * size # Simulated hash table
def _hash(self, key):
return hash(key) % self.size # Simulate Python's hash function
def insert(self, key, value):
index = self._hash(key)
while self.table[index] is not None:
if self.table[index][0] == key: # Update value if key exists
self.table[index] = (key, value)
return
index = (index + 1) % self.size # Linear probing
self.table[index] = (key, value)
def display(self):
print(self.table)
# Example usage
d = SimpleDict()
d.insert(1, "One")
d.insert(6, "Six") # Hash collision if size=5 (1 and 6 share index)
d.display()
* Uses linear probing to handle collisions.
Concept | Python Dictionary Handling |
---|---|
Hashing | hash(key) % table_size |
Collisions | Open Addressing (Probing) |
Probing Strategy | Linear or Quadratic Probing |
Resizing | Doubles size to reduce collisions |