Sort Python dict by datetime value

I have a Python dictionary, for example:

{ '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 a dictionary by datetime values? I am looking for list output with keys from the most recent to the oldest.

+6
source share
4 answers

You can sort the keys as follows:

 sorted(dct, key=dct.get) 

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

+11
source

Whereas the question asks how to sort by date and time, here you can 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 are only interested in keys:

 [k for k, v in sorted(dct.items(), key=lambda p: p[1], reverse=True)] => ['raspberry', 'apple', 'orange'] 
+1
source

It is very simple, you just do something like:

  from operator import itemgetter sorted(a.items(),key=itemgetter(1),reverse=True) 
0
source

Try to get a list of keys, as shown below for the dict dictionary:

 [item[0] for item in sorted(dict.items(), key=lambda val: val[1])] 
0
source

Source: https://habr.com/ru/post/951407/


All Articles