Data Structures

How do you implement a hash table in Python?

Hard
5
Added
A hash table is a data structure that implements an associative array abstract data type, a structure that can map keys to values. It uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.

Solution Code

Data Structures
class HashTable:
    def __init__(self, size=10):
        self.size = size
        self.table = [[] for _ in range(size)]

    def _hash(self, key):
        return hash(key) % self.size

    def insert(self, key, value):
        index = self._hash(key)
        bucket = self.table[index]
        for i, (k, v) in enumerate(bucket):
            if k == key:
                bucket[i] = (key, value)
                return
        bucket.append((key, value))

    def get(self, key):
        index = self._hash(key)
        bucket = self.table[index]
        for k, v in bucket:
            if k == key:
                return v
        return None

# Example usage
hash_table = HashTable()
hash_table.insert("key1", "value1")
print(hash_table.get("key1"))
Explanation
This code snippet demonstrates how to implement a hash table in Python.

Guided Hints

Define a HashTable class
Implement a hash function
Use a list of lists to handle collisions