Sorting dictionary by datetime value

Frank Millman frank at chagford.com
Sat Feb 8 09:22:05 CET 2014


"Frank Millman" <frank at chagford.com> wrote in message 
news:ld4ocf$9rg$1 at ger.gmane.org...
>
> "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.
>

As Chris replied in another post -

> The problem here is actually your key function. my_dict.items()
> returns a series of two-item tuples, none of which exists in your
> dictionary; so you're actually sorting [None, None, None], which isn't
> very useful.
>
> Try this:
>
> sorted_items = sorted(my_dict.keys(), key=my_dict.get)
> for key in sorted_items:
>    print my_dict[key], key
>

Without realising it, you have answered all my questions - thanks very much.

Frank






More information about the Python-list mailing list