Sorting dictionary by datetime value

Larry Hudson orgnut at yahoo.com
Sun Feb 9 00:33:15 EST 2014


On 02/07/2014 11:06 PM, Igor Korot wrote:
> Hi, ALL,
> I'm trying to do a very easy task: sort python dictionary by value
> where value is a datetime object.
>
> When trying to do that in Python shell everthing works as expected.
>
> C:\Documents and Settings\Igor.FORDANWORK>python
> Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> a = {}
>>>> import datetime
>>>> a['1'] = datetime.datetime(2012,12,28,12,15,30,100)
>>>> a['2'] = datetime.datetime(2012,12,28,12,17,29,100)
>>>> a['3'] = datetime.datetime(2012,12,28,12,16,44,100)
>>>> 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.
>
> I am trying to run it on Windows XP and the data are coming from the DB.
>
> What am I missing?
>
> Thank you.
>

You are missing the difference between sorted and sort.

The sorted function returns a new list, but leaves the original unchanged.
The sort method changes the list in place, and returns None.

In your first, interactive example, the returned sorted list is automatically displayed -- 
that's why you see the sorted list.  In your script, however, you are sorting the list but not 
saving the result -- it's immediately thrown away.  In effect, your "sorted(...)" line is a 
no-op.  You follow this by displaying the original, unsorted dictionary.

Secondly, your sorting key is wrong.  You are sorting a list not a dictionary.  It is a list of 
(key,value) tuples, which you want to sort on the second element of the tuple.  You can do this 
with a simple lambda expression:  key=lambda t:t[1]

Finally, change your for loop to print the data from this sorted list of tuples, not from the 
dictionary.

      -=- Larry -=-




More information about the Python-list mailing list