Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do comparison operators do on dictionaries?

I came across this:

>>> d1 = {"john":40, "peter":45}
>>> d2 = {"john":466, "peter":45}
>>> d1 > d2
False

What does the comparison operator do while comparing two dicts and how does it output False?

like image 202
Adarsh Kumar Avatar asked Mar 23 '26 08:03

Adarsh Kumar


1 Answers

Since these dicts have equal length, we find the smallest key for which the corresponding values are unequal, i.e. 'john'. Then the dicts are compared on the value of that key.

Demo:

>>> d1 = {"john":40, "peter":45}
>>> d2 = {"john":466, "peter":45}
>>> d1 < d2
True
>>> d2['john'] = 39
>>> d1 < d2
False

This basic idea is essentially unchanged since Guido's commit from over 20 years ago:

$ git show a0a69b8
commit a0a69b8b429f3d4c91f1c432247cfda017505976
Author: Guido van Rossum <[email protected]>
Date:   Thu Dec 5 21:55:55 1996 +0000

    Experimental new implementation of dictionary comparison.  This
    defines that a shorter dictionary is always smaller than a longer one.
    For dictionaries of the same size, the smallest differing element
    determines the outcome (which yields the same results as before,
    without explicit sorting).

It is not documented, and the dict comparison code is removed in Python 3, so I wouldn't rely on that for anything important. The relevant CPython source is here.

Fun fact: Apparently, in older versions of Python, some dict comparisons could crash the runtime and could even cause Windows 98 to reboot. Heh.

like image 165
wim Avatar answered Mar 24 '26 21:03

wim