0% found this document useful (0 votes)
6 views1 page

Python Hash Table Implementation

The document defines a HashTable class that implements basic hash table operations including insertion, searching, deletion, and displaying the contents. It uses a simple hash function based on the modulo of the key and supports handling collisions through chaining. The provided example demonstrates inserting, searching, and deleting keys in the hash table.

Uploaded by

Tejas Sarangdhar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Python Hash Table Implementation

The document defines a HashTable class that implements basic hash table operations including insertion, searching, deletion, and displaying the contents. It uses a simple hash function based on the modulo of the key and supports handling collisions through chaining. The provided example demonstrates inserting, searching, and deleting keys in the hash table.

Uploaded by

Tejas Sarangdhar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

class HashTable:

def __init__(self, size=10):


[Link] = size
[Link] = [[] for _ in range(size)]

def _hash_function(self, key):


return key % [Link]

def insert(self, key, value):


index = self._hash_function(key)
for pair in [Link][index]:
if pair[0] == key:
pair[1] = value
print(f"Updated key {key} with value {value}")
return

[Link][index].append([key, value])
print(f"Inserted key {key} with value {value}")

def search(self, key):


index = self._hash_function(key)
for pair in [Link][index]:
if pair[0] == key:
return pair[1]
return None

def delete(self, key):


index = self._hash_function(key)
for i, pair in enumerate([Link][index]):
if pair[0] == key:
del [Link][index][i]
print(f"Deleted key {key}")
return
print(f"Key {key} not found for deletion.")

def display(self):
print("Hash Table:")
for i, bucket in enumerate([Link]):
print(f"Index {i}: {bucket}")

ht = HashTable()

[Link](15, "apple")
[Link](25, "banana")
[Link](35, "cherry")
[Link](67,"blueberry")
[Link](95,"green apple")
print("Search 25:", [Link](25))
[Link](25)
print("Search 25 after deletion:", [Link](25))
[Link](15)
print("Search 15 after deletion:",[Link](15))
[Link]()

You might also like