Why aren't OrderedDicts comparable with < etc?

Mark list at qtrac.plus.com
Thu Jul 16 12:59:47 CEST 2009


On 16 July, 11:58, Mark <l... at qtrac.plus.com> wrote:
> On 16 July, 08:51, Steven D'Aprano
>
>
>
> <ste... at REMOVE.THIS.cybersource.com.au> wrote:
> > On Thu, 16 Jul 2009 00:30:26 -0700, Chris Rebert wrote:
> > > On Wed, Jul 15, 2009 at 11:21 PM, Mark Summerfield<l... at qtrac.plus.com>
> > > wrote:
> > >> Hi,
>
> > >> I'm just wondering why <, <=, >=, and > are not supported by
> > >> collections.OrderedDict:
>
> > >>    >>> d1 = collections.OrderedDict((("a",1),("z",2),("k",3))) d2 =
> > >>    >>> d1.copy()
> > >>    >>> d2["z"] = 4
> > >>    >>> d1 == d2
> > >>    False
> > >>    >>> d1 < d2
> > >>    Traceback (most recent call last):
> > >>    File "<pyshell#6>", line 1, in <module>
> > >>        d1 < d2
> > >>    TypeError: unorderable types: OrderedDict() < OrderedDict()
>
> > >> It just seems to me that since the items in ordered dictionaries are
> > >> ordered, it would make sense to do an item by item comparison from
> > >> first to last item in exactly the same way that Python compares lists
> > >> or tuples?
>
> > > Use case? I'm curious.
>
> > Surely it would be the same use case as for comparing two lists? There
> > doesn't need to be a special "OrderedDict use case" beyond "an
> > OrderedDict is just like a list of (key,value) tuples, but searches are
> > faster".
>
> > Or maybe not. If OrderedDicts are sequences as well as mappings, then we
> > should be able to sort them. And that seems a bit much even for me.
>
> > --
> > Steven
>
> One thing that I've just noticed is that you can use <, <=, >=, and >
> with sets:
>
> >>> s1 = {1,2,3}
> >>> s2 = {1,2,4}
> >>> s1 == s2
> False
> >>> s1 < s2
> False
> >>> s1 <= s2
> False
> >>> s2 < s1
> False
> >>> s2 <= s1
> False
> >>> s1 != s2
>
> True
>
> It seems a bit inconsistent that with sets you always get False when
> using an ordering operator but with an ordered dict you get an
> exception?

Ooops---disregard the above---I forgot that these do subset and
superset comparisions!



More information about the Python-list mailing list