Sorting dictionary by datetime value

Chris Angelico rosuav at gmail.com
Sat Feb 8 08:58:29 CET 2014


On Sat, Feb 8, 2014 at 6:53 PM, Igor Korot <ikorot01 at gmail.com> wrote:
> Chris,
>
> On Fri, Feb 7, 2014 at 11:09 PM, Chris Angelico <rosuav at gmail.com> wrote:
>> 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))]
>>>>>>
>>>
>>> However, trying to do the same thing from the script does not sort the
>>> dictionary:
>>>
>>> sorted(my_dict.items(), key=my_dict.get, reverse=False)
>>> for key, value in my_dict.items():
>>>      print value, key
>>>
>>> the dictionary prints with unsorted items.
>>
>> The sorted() function returns a sorted list. You're then going back to
>> the original dictionary. Instead, just iterate over the sorted items:
>>
>> items = sorted(my_dict.items(), key=my_dict.get, reverse=False)
>> for key, value in items:
>>     print value, key
>
> Still does not work. It prints:
>
> =======
> DATE TIME - EVENT
> 058f63666438&0  - Instance ID
> Original values
> 2013-11-15 15:42:27.000499 User Datetime
> 2013-07-14 16:42:18.000637 Property Keys
> 2013-11-15 15:42:17.000938 Volume Device
> 2013-07-14 16:42:22.000276 Last Modify Reg Times 1
> Sorted values
> 2013-11-15 15:42:27.000499 User Datetime
> 2013-07-14 16:42:18.000637 Property Keys
> 2013-11-15 15:42:17.000938 Volume Device
> 2013-07-14 16:42:22.000276 Last Modify Reg Times 1
>
> Code is as follows:
>
> sorted_items = sorted(my_dict.items(), key=my_dict.get, reverse=False)
> print row[19], " - Instance ID"
> print "Original values"
> for key, value in my_dict.items():
>      print value, key
> print "Sorted values"
> for key, value in sorted_items:
>      print value, key
>
> Thank you.

Assuming you sent that privately only by mistake - hope you don't mind
me responding on-list.

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

Note that reverse=False is the default, so you don't need to specify that.

ChrisA



More information about the Python-list mailing list