27

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.

Gus
  • 1,797
  • 4
  • 20
  • 36

4 Answers4

20

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.

unutbu
  • 777,569
  • 165
  • 1,697
  • 1,613
3

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']
Óscar López
  • 225,348
  • 35
  • 301
  • 374
0

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

 from operator import itemgetter
 sorted(a.items(),key=itemgetter(1),reverse=True)
Pawel Miech
  • 7,373
  • 3
  • 33
  • 54
0

Try getting list of keys as below for dictionary dict:

[item[0] for item in sorted(dict.items(), key=lambda val: val[1])]
Satish
  • 16
  • 5