Sort Python dict by datetime value

Question:

I have a Python dictionary like this:

{
   'apple': datetime.datetime(2012, 12, 20, 0, 0, tzinfo=<UTC>),
   'orange': datetime.datetime(2012, 2, 4, 0, 0, tzinfo=<UTC>),
   'raspberry': datetime.datetime(2013, 1, 9, 0, 0, tzinfo=<UTC>)
}

What is the best way to sort the dictionary by the datetime values? I am looking for a list output with the keys in order from most recent to oldest.

Asked By: Gus

||

Answers:

You could sort the keys like this:

sorted(dct, key=dct.get)

See the Sorting Mini-HOW TO for an explanation of this and other techniques for sorting.

Answered By: unutbu

Bearing in mind that the question asks how to sort by the datetime values, here’s a possible answer:

sorted(dct.items(), key=lambda p: p[1], reverse=True)

=> [('raspberry', datetime.datetime(2013, 1, 9, 0, 0)),
    ('apple', datetime.datetime(2012, 12, 20, 0, 0)),
    ('orange', datetime.datetime(2012, 2, 4, 0, 0))]

If you’re only interested in the keys:

[k for k, v in sorted(dct.items(), key=lambda p: p[1], reverse=True)]

=> ['raspberry', 'apple', 'orange']
Answered By: Óscar López

It is really easy, you just do, something like:

 from operator import itemgetter
 sorted(a.items(),key=itemgetter(1),reverse=True)
Answered By: Pawel Miech

Try getting list of keys as below for dictionary dict:

[item[0] for item in sorted(dict.items(), key=lambda val: val[1])]
Answered By: Satish
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.