Engineering Insights | BJSS

Make More of Python Dictionary Keys with a Bidictionary

Written by Dan Childs | Aug 12, 2021 12:06:18 PM

The Python dictionary data structure is powerful. But to get the most out of it, you need to think about the data a dictionary stores and how you want to use it. In other words, as with all programming, you’ve got to think from the outside in, not the inside out. You’ve got to know what the point of all the data in the dictionary is, what it’s going to be used for, and how you want to structure and query it.

With that in mind, let’s take a look at a data structure problem using Python dictionary keys and values, with a really practical example.

what is a dictionary for?

First, a digression. Let’s think about the word ’‘literally'. That guy on the Zoom call who said he is ‘literally melting in this heat'. Is he in need of urgent medical attention, or is there a different meaning of this word?

In the old days, to check the meaning of ‘literally’ you would pull out a dictionary, a meaty doorstep of knowledge. How would you find a single word in something that has 3,000 pages?

One way would be to start at the first page, check all the words on that page, and then try the next page until you find the page with your word on it. But this would be crazy! There is a more efficient algorithm for using a paper dictionary. All the words are listed alphabetically, so you’d open the book roughly halfway, where you guess the ‘L’ section might be, flip back and forth a little until you get to words starting with ’‘Li', then look more closely for ‘literally’.

The time difference between starting at page one and carefully scanning every word and flicking to where you know ‘literally’ will be in the dictionary is huge. Seconds versus many hours.