Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of dictionaries by date in Python 3.4 [duplicate]

I have a list of dictionaries like this but with many more dictionaries:

x = [{"duration":datetime.time(5,30),"date":datetime.date(2016,02,13)},{"duration":datetime.time(3,30),"date":datetime.date(2016,02,11)},{"duration":datetime.time(2,0),"date":datetime.date(2016,02,16)}]

Is there a way to sort this list in ascending order of date using Python keywords such as sorted and lambda without making a custom sorting function? I have been looking at the sorted docs and the use of lambda in the optional key argument.

like image 890
Rob Murray Avatar asked Feb 04 '16 10:02

Rob Murray


People also ask

How do I sort a list of dictionaries in Python 3?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function. See the following article for more information.

Are Python dictionaries automatically sorted?

It is not sorting. dict is not ordered at all, so you cannot influence the key order in any way. There is collections.


1 Answers

While posting the question I figured out the answer so thought I should share.

x = sorted(x, key = lambda k: k["date"])
like image 92
Rob Murray Avatar answered Oct 05 '22 03:10

Rob Murray