Python Surprises Series — Episode 1: The Unexpected Behavior of Dictionary Value Comparisons

Leo Liu
2 min readJan 7, 2024

Decoding Python’s Hidden Quirks: Unraveling the Mystery Behind Dictionary Value Comparisons

Welcome to the first entry in our “Python Surprises” series, where we dive into the intriguing and often unexpected behaviors of Python that can catch even seasoned developers off guard. Today’s topic is a simple, yet baffling, case: comparing the values of two dictionaries.

Consider the following Python dictionaries:

dict1 = {'a': 1, 'b': 2}
dict2 = {'a': 1, 'b': 2}

At a glance, these dictionaries are identical. So, it stands to reason that comparing their values should confirm this. Let’s try it out:

print(dict1.values() == dict2.values())
False

Intuitively, you might expect this to print True. After all, both dict1 and dict2 have the same values, right? But, surprise! The output is False. Let's explore why this happens and how we can navigate this unexpected behavior.

Unpacking the Mystery

The root of this surprise lies in how Python’s dictionary values are stored and compared. When you call .values() on a dictionary, Python doesn't return a list or a straightforward collection of…

--

--

Leo Liu

Full stack Software Engineer | Quantitative Developer | Data Scientist. Leveraging Data Science and AI to solve tech challenges.