Sorting dictionary by datetime value

Peter Otten __peter__ at web.de
Sat Feb 8 09:27:20 CET 2014


Frank Millman wrote:

> 
> "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.

Chris has already explained it. Here you can watch the key calculation at 
work:

>>> d = {'1': 'abc', '2': 'xyz', '3': 'pqr'}
>>> def sortkey(value):
...     key = d.get(value)
...     print "value:", value, "sort-key:", key
...     return key
... 
>>> sorted(d.items(), key=sortkey)
value: ('1', 'abc') sort-key: None
value: ('3', 'pqr') sort-key: None
value: ('2', 'xyz') sort-key: None
[('1', 'abc'), ('3', 'pqr'), ('2', 'xyz')]

Can you change the dict to make d.get return non-None values? 

The OP was probably trying to mimic sorted(d, key=d.get) which sorts the 
dict keys by the associated dict values:

>>> sorted(d, key=sortkey)
value: 1 sort-key: abc
value: 3 sort-key: pqr
value: 2 sort-key: xyz
['1', '3', '2']





More information about the Python-list mailing list