Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Python dict by datetime value [duplicate]

Tags:

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.

like image 985
Gus Avatar asked Aug 09 '13 17:08

Gus


People also ask

Can you sort a dictionary by value in Python?

To correctly sort a dictionary by value with the sorted() method, you will have to do the following: pass the dictionary to the sorted() method as the first value. use the items() method on the dictionary to retrieve its keys and values. write a lambda function to get the values retrieved with the item() method.

Does dict items return in order?

Python OrderedDict is a dict subclass that maintains the items insertion order. When we iterate over an OrderedDict, items are returned in the order they were inserted. A regular dictionary doesn't track the insertion order. So when iterating over it, items are returned in an arbitrary order.


2 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.

like image 135
unutbu Avatar answered Oct 12 '22 17:10

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'] 
like image 35
Óscar López Avatar answered Oct 12 '22 17:10

Óscar López