Sorting dictionary by datetime value

Chris Angelico rosuav at gmail.com
Sat Feb 8 09:18:08 CET 2014


On Sat, Feb 8, 2014 at 7:03 PM, Frank Millman <frank at 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



More information about the Python-list mailing list