Sorting dictionary by datetime value

Frank Millman frank at chagford.com
Sat Feb 8 09:03:42 CET 2014


"Chris Angelico" <rosuav at gmail.com> wrote in message 
news:CAPTjJmqDusdFC1eLbU6LF5-up__LAE-63ii0UUvAGGNem9U4+w at mail.gmail.com...
> On Sat, Feb 8, 2014 at 6:06 PM, Igor Korot <ikorot01 at gmail.com> wrote:
>>>>> sorted(a.items(), key=a.get)
>> [('1', datetime.datetime(2012, 12, 28, 12, 15, 30, 100)), ('3', 
>> datetime.datetim
>> e(2012, 12, 28, 12, 16, 44, 100)), ('2', datetime.datetime(2012, 12, 28, 
>> 12, 17,
>>  29, 100))]

That seemed like a neat trick, so I thought I would try to understand it a 
bit better in case I could use it some day.

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()
>>>

I know that python3 is stricter regarding ordering of non-comparable types, 
but I don't see where None is coming from.

I have python 2.7.3 on another machine. Here are the results -

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

It did not crash, but it did not sort.

Then I changed the keys to strings, to match Igor's example -

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

It works - now I am even more confused.

Any hints will be appreciated.

Frank Millman






More information about the Python-list mailing list