Why aren't OrderedDicts comparable with < etc?

Jack Diederich jackdied at gmail.com
Tue Jul 21 02:42:02 EDT 2009


On Mon, Jul 20, 2009 at 10:00 AM, Steven
D'Aprano<steve at remove-this-cybersource.com.au> wrote:
> On Mon, 20 Jul 2009 09:34:24 +0000, Sion Arrowsmith wrote:
>
>> Terry Reedy  <tjreedy at udel.edu> wrote:
>>>Sion Arrowsmith wrote:
>>>> Jack Diederich  <jackdied at gmail.com> wrote:
>>>>> It isn't an OrderedDict thing, it is a comparison thing.  Two regular
>>>>> dicts also raise an error if you try to LT them.
>>>> Python 2.5.2
>>>>>>> d1 = dict((str(i), i) for i in range (10)) d2 = dict((str(i), i)
>>>>>>> for i in range (20)) d1 < d2
>>>> True
>>>Try reversing the definitions of d1 and d2. The dicts are probably being
>>>compared by id (address), which is the 2.x CPython default.
>>
>> Like this?
>>
>>>>> d1 = dict((str(i), i) for i in range (20))
>>>>> d2 = dict((str(i), i) for i in range (10))
>>>>> d1 < d2
>> False
>>>>> id(d1) < id(d2)
>> True
>>
>> I didn't know that comparison for anything other than equality defaulted
>> to using id. That really is rather broken, and I'm glad 3.0 fixed it.
>
>
> I don't think comparisons other than equality use id. That would be
> rather insane. If anyone can demonstrate such comparisons in a built-in
> or standard library class, I'd like to see it.
>
>
> For the record, dicts have been comparable with < and > since at least
> Python 1.5:
>
> $ python1.5
> Python 1.5.2 (#1, Apr  1 2009, 22:55:54)  [GCC 4.1.2 20070925 (Red Hat
> 4.1.2-27)] on linux2
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>>
>>>> {1: 'a', 2: 'b'} < {2: 'b', 3: 'a'}
> 1
>
>
> Reading the docs:
>
> http://docs.python.org/library/stdtypes.html#comparisons
> http://docs.python.org/library/stdtypes.html#mapping-types-dict
>
> I can only suggest that dicts compare in an arbitrary but consistent
> fashion.

I should have specified 3.x but since we were talking about
OrderedDicts (only in 3.1) I didn't say it explicitly.   Earlier
versions of python were very permissive with comparisons -- it was
rare that any cmp() raised an error and the ultimate fallback was on
the object's id.  This is one of the non-backwards compatible changes
in 3k.  Now comparing two of the same thing that don't have an obvious
ordering is an error.  Is a dict "greater than" if it has a larger
size?  if its max key is larger?  what does "max key" mean when the
keys aren't even comparable?.  Comparing things that aren't extremely
similar is an error now also.

-Jack



More information about the Python-list mailing list