Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Python list of objects by date

I have a Python list called results. Each result in the results list has a person object, and each person object has a birthdate (result.person.birthdate). The birthdate is a datetime object.

I would like to order the list by birthdate with the oldest first. What is the most Pythonic way to do this?

like image 536
shane Avatar asked Feb 20 '11 07:02

shane


People also ask

How do you sort a list of elements?

sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator. Set the reverse parameter to True, to get the list in descending order.

Can you sort a list of objects in Python?

A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.

How do I sort list of datetime?

You only need to call a. sort() without assigning it to a again. There is a built in function sorted() , which returns a sorted version of the list - a = sorted(a) will do what you want as well.


1 Answers

results.sort(key=lambda r: r.person.birthdate) 
like image 164
Amber Avatar answered Sep 21 '22 23:09

Amber