Why aren't OrderedDicts comparable with < etc?

Piet van Oostrum piet at cs.uu.nl
Thu Jul 16 05:21:54 EDT 2009


>>>>> Mark <list at qtrac.plus.com> (M) wrote:

>M> You are right that it doesn't make sense to compare two dicts.

>M> But OrderedDicts can be viewed logically as lists of (key,value)
>M> tuples so they are much more like lists or tuples when it comes to
>M> comparisons.

>M> For example:

>>>>> l = [("a", 1), ("z", 2), ("k", 3)]
>>>>> l1 = l[:]
>>>>> l1[1] = ("z", 5)
>>>>> l < l1
>M> True

>M> But if you do:

>>>>> d = collections.OrderedDict(l)
>>>>> d1 = collections.OrderedDict(l1)

>M> You can't use <, <=, =>, or >, even though ordered dictionaries
>M> preserve the order and their items are just as comparable as those in
>M> a list or tuple of tuples.

But why should the order be as if the OrderedDict was a list of tuples.
A dict can be considered as a mapping and then you might want to treat
either the key or the value as contravariant (the key I guess). So there
is ambiguity. Why would the view as a list of tuples for the ordering be
the `natural' view? 

Maybe you may expect some kind of monotonicity such that d1<d2 implies
d1[x]<d2[x], but that doesn't work for d1 = {1:10, 2:20} and d2 = {1:15,
2:5}. So maybe there is only a partial ordering?

-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list