And my simplified explanation of the solution

side of a building with a big question mark sign
Photo by Lidia Zajdzińska on Unsplash

Recently I subscribed to Dan Bader’s blog. Every few days he sends out a cute or interesting Python code snippet. Last week a riddle arrived! Who doesn’t love a good brain teaser?!? Here’s Dan’s riddle:

What will this expression evaluate to?

(I’m not going to leave you hanging; the answer is at the bottom of this post.)

Monkey hanging by one arm from a tree
Monkey hanging by one arm from a tree
Photo by Lisa Kohnen on Unsplash

Dan included a link with the riddle to a very thorough (and somewhat technical) explanation and can be found here. I’ve read the explanation several times and can understand some of it. However, once the explanation got into stuff about “hash” my eyes glazed over. Just a wee bit too much for me.

So, in my own words, below is how I explain the answer to the riddle.

Let’s start the beginning: What is a Python dictionary? It is a collection of items that is unordered, mutable, has keys and values, and is enclosed in curly braces. Dan’s riddle has keys and values and is in curly braces — it’s a dictionary! So far, we’re good.

What does it mean that a dictionary is mutable? If I want to add to the riddle dictionary, that’s possible and that makes it mutable (able to be changed). Let’s assign the riddle dictionary to a variable:

riddle_dict = {True: ‘yes’, 1: ‘no’, 1.0: ‘maybe’}

To add to it the riddle_dict:

riddle_dict[new_key] = value

To delete that new key simply:

del riddle_dict[new_key]

Another feature of a dictionary that is key to this riddle (pun intended!) is that dictionaries do not support duplicate keys. The key is used as a unique identifier in a dictionary. If I tried to add a key-value pair, but the key already existed, Python simply updates the value of the key in the dictionary with the new value.

AND, finally, the real kicker is that in Python, True is equal to 1.0 and 1.

Python code

Since the riddle keys are equal and Python does not support duplicate keys, the dictionary key is updated with the new value. Therefore, the answer to the riddle is:

{True: ‘maybe’}