-1

Just curious, nothing more. Why were dictionary magnitude comparisons (> < >= <=) removed in Python3? What's the reason that brought to delete them?

For example: dictA > dictB

zer0uno
  • 7,521
  • 13
  • 57
  • 86

1 Answers1

3

Arbitrary comparison ordering was removed from Python 3, see Ordering Comparisons in the What's New in Python 3.0 documentation.

There is no meaningful natural ordering between dictionaries. Python 2 only pretended there was to play nice with sorting mixed lists, but this only led to enormous confusion.

Take comparing strings with integers for example; integers are always smaller than strings in Python:

>>> 10 < "10"
True

Many a beginner will try to compare strings with integers anyway; it is natural to use number = raw_input('Pick a number! ') and then try to compare this with an integer; and sometimes this will look like it is working! In Python 3 this is now an error.

The same applies to the majority of objects; unless they explicitly define comparison methods (__lt__, __gt__, etc.) the types are not orderable. This includes dictionaries.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • According to "Learning Python" by Mark Lutz: "magnitude comparisons for dictionaries are removed in Python 3.X because they incur too much overhead when equality is desired". So I don't get, were they removed for meaningful reason or performance reason? – zer0uno Jul 22 '14 at 18:59
  • @antox: The Python 2 comparison code was rather arbitrary; there is no natural order for dictionaries. I don't agree with Lutz's assertion as to why this was removed. – Martijn Pieters Jul 22 '14 at 19:04
  • I don't know if it can help but it continues saying: "...when eqaulity is desired (equality uses an optimized scheme in 3.X that doesn't literally compare sorted key/value lists)" – zer0uno Jul 22 '14 at 19:06
  • @antox: The [Python 3 version of `dict_equal()`](http://hg.python.org/cpython/file/bf1b0afe419b/Objects/dictobject.c#l2130) is essentially no different from the [version in Python 2](http://hg.python.org/cpython/file/5549075d6223/Objects/dictobject.c#l1840); it is only the `dict_compare` implementation in Python 2 that is really different here (and absent in Py 3). – Martijn Pieters Jul 22 '14 at 20:45