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.
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.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With