Hash Tables for Speed

While hash tables are a perfect fit for paired data, they can also be used to make your code faster—even if your data doesn’t exist as pairs. And this is where things get exciting.

Here’s a simple array:

 array = [61, 30, 91, 11, 54, 38, 72]

If you want to search for a number in this array, how many steps would it take?

Because the array is unordered, you’d have to perform a linear search, which would take N steps—you learned this back at the beginning of the book.

However, what would happen if we ran some code that would convert these numbers into a hash table that looked like this?

 hash_table = {61: True, 30: True, 91: True,
 11: True, 54: True, 38: True, 72: True}

Here, we’ve stored each number as a key and assigned ...

Get A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.