Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #65642

Re: Sorting dictionary by datetime value

References <CA+FnnTxTvmSu922+Cg83jp8O_XdXXVnhQ1zaDEOd_41bONcoRQ@mail.gmail.com> <CAPTjJmqDusdFC1eLbU6LF5-up__LAE-63ii0UUvAGGNem9U4+w@mail.gmail.com> <ld4ocf$9rg$1@ger.gmane.org>
Date 2014-02-08 19:18 +1100
Subject Re: Sorting dictionary by datetime value
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.6520.1391847492.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Sat, Feb 8, 2014 at 7:03 PM, Frank Millman <frank@chagford.com> wrote:
> I am using python3. I don't know if that makes a difference, but I cannot
> get it to work.
>
>>>> d = {1: 'abc', 2: 'xyz', 3: 'pqr'}
>>>> sorted(d.items(), key=d.get)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: unorderable types: NoneType() < NoneType()
>>>>

You probably hadn't seen my subsequent post yet, in which I explain
what's going on here.

In Python 2, "None > None" is simply False. (So is "None < None",
incidentally.) Py3 makes that an error. But in all your examples,
you're effectively trying to sort the list [None, None, None], which
is never going to be useful. What you can do, though, is either sort
items using itemgetter to sort by the second element of the tuple, or
sort keys using dict.get.

Using 3.4.0b2:

>>> d = {1: 'abc', 2: 'xyz', 3: 'pqr'}
>>> sorted(d.keys(), key=d.get)
[1, 3, 2]

You don't get the values that way, but you get the keys in their
correct order, so you can iterate over that and fetch the
corresponding values. Alternatively, this is a bit more verbose, but
works on items():

>>> import operator
>>> sorted(d.items(), key=operator.itemgetter(1))
[(1, 'abc'), (3, 'pqr'), (2, 'xyz')]

operator.itemgetter(1) returns a callable that, when passed some
object, returns that_object[1].

ChrisA

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Sorting dictionary by datetime value Chris Angelico <rosuav@gmail.com> - 2014-02-08 19:18 +1100

csiph-web