How a Hash Table Works

Build a tiny dictionary: a hash function picks a bucket for each key. "cat" and "act" land in the same bucket: a collision.

Python · intermediate · 8 min · 37 steps · free

What you'll learn

hash_table.py

class HashTable:
    def __init__(self):
        self.buckets = [[], [], [], []]

    def index(self, key):
        return sum(map(ord, key)) % len(self.buckets)

    def put(self, key, value):
        bucket = self.buckets[self.index(key)]
        bucket.append([key, value])

    def get(self, key):
        for pair in self.buckets[self.index(key)]:
            if pair[0] == key:
                return pair[1]
        return None

table = HashTable()
table.put('cat', 3)
table.put('dog', 1)
table.put('act', 5)
print(table.get('act'))

Step by step

  1. Python starts building the class HashTable. Its methods are stored, but none of them run yet.
  2. Python reads the class body: everything indented under class HashTable belongs to it.
  3. The method __init__ is stored in HashTable. It runs only when it is called on an object.
  4. The method index is stored in HashTable. It runs only when it is called on an object.
  5. The method put is stored in HashTable. It runs only when it is called on an object.
  6. The method get is stored in HashTable. It runs only when it is called on an object.
  7. The class HashTable is now defined, ready to make objects from.
  8. Python calls __init__(), with self = {}. It gets its own names.
  9. A new key buckets with the value a list is added to the HashTable that self points to.
  10. __init__() has finished, so its names are gone. The value it returned, {buckets: a list}, is stored in table.
  11. Python calls put(), with self = {buckets: a list}, key = 'cat' and value = 3. It gets its own names.
  12. Python calls index(), with self = {buckets: a list} and key = 'cat'. It gets its own names.
  13. The hash function adds up the letter codes of "cat" (99 + 97 + 116 = 312) and takes the remainder by 4: bucket 0.
  14. index() has finished, so its names are gone. The value it returned, [], is stored in bucket.
  15. ["cat", 3] goes into bucket 0.
  16. put() has finished, so its names are gone.
  17. Python calls put(), with self = {buckets: a list}, key = 'dog' and value = 1. It gets its own names.
  18. Python calls index(), with self = {buckets: a list} and key = 'dog'. It gets its own names.
  19. The function returns sum(map(ord, key)) % len(self.buckets).
  20. index() has finished, so its names are gone. The value it returned, [], is stored in bucket.
  21. a list is added to the end of the list that bucket points to.
  22. put() has finished, so its names are gone.
  23. Python calls put(), with self = {buckets: a list}, key = 'act' and value = 5. It gets its own names.
  24. Python calls index(), with self = {buckets: a list} and key = 'act'. It gets its own names.
  25. The function returns sum(map(ord, key)) % len(self.buckets).
  26. index() has finished, so its names are gone. The value it returned, [a list], is stored in bucket.
  27. "act" has the same letters, so the same sum: bucket 0 again. A collision: both pairs share the bucket.
  28. put() has finished, so its names are gone.
  29. Python calls get(), with self = {buckets: a list} and key = 'act'. It gets its own names.
  30. Python calls index(), with self = {buckets: a list} and key = 'act'. It gets its own names.
  31. The function returns sum(map(ord, key)) % len(self.buckets).
  32. index() has finished, so its names are gone. The value it returned, ['cat', 3], is stored in pair.
  33. pair[0] == key is false, so the block under it is skipped.
  34. pair now points to a different list: ['act', 5].
  35. The second pair in bucket 0 is "act": return 5.
  36. The function returns pair[1].
  37. get() has finished, so its names are gone. It prints 5.

Common mistakes

Best practices

Key takeaways

Check yourself

Why can lists not be dict keys in Python?

Answer: They can change, so their hash would change

Average lookup cost?

Answer: O(1)

·

More in Lists, Stacks, Queues and Hashing