Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Python list of objects by date (when some are None)

This is a slight update to my previous question

I have a Python list called results. Most result objects in the results list have a person object, and most person objects have a birthdate property (result.person.birthdate). The birthdate is a datetime object.

I would like to order the list of results by birthdate with the oldest first. However, if there isn't a person object or the person object doesn't have a birthdate I would still like the result included in the list of results. At the end of the list would be ideal.

What is the most Pythonic way to do this?

like image 560
shane Avatar asked Feb 20 '11 08:02

shane


1 Answers

def birthdate_key(x):
  missing = (x.person is None or x.person.birthdate is None)
  return (missing, x.person.birthdate if not missing else None)

results.sort(key=birthdate_key)
like image 61
Thomas Edleson Avatar answered Sep 20 '22 13:09

Thomas Edleson