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.
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.
It is not sorting. dict is not ordered at all, so you cannot influence the key order in any way. There is collections.
While posting the question I figured out the answer so thought I should share.
x = sorted(x, key = lambda k: k["date"])
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