Sorting dictionary by datetime value

Igor Korot ikorot01 at gmail.com
Sat Feb 8 08:06:37 CET 2014


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.



More information about the Python-list mailing list