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

This is a small update to my previous question.

I have a Python list called the result. Most result objects have a person object in the result list, and most human objects have the birthdate property (result.person.birthdate). Date of birth is a datetime object.

I would like to order a list of results by date of birth with the oldest first. However, if there is no human object or the human object does not have a date of birth, I will still like the result included in the list of results. At the end of the list would be perfect.

What is the most pythonic way to do this?

+6
python sorting list
source share
5 answers
import datetime results.sort(key=lambda r: r.person.birthdate if (r and r.person and r.person.birthdate) else datetime.datetime.now()) 

(PS Perhaps you just edited your previous question.)

+8
source share
 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) 
+2
source share

I interpret "if there is no human object or the human object does not have a birth date" means that if the result object does not have the "person" attribute, and also result.person object doesn 't have the' birthdate 'attribute. However, I notice that your previous question uses strange terminology, such as "person object set to None" (in the comment). How to set an object in None? Do you mean the person attribute set to None? When you ask a question, (1) please make it standalone and (2) fully explain what your actual data structure is.

 import datetime large_date = datetime.datetime(9999, 12, 31) results.sort(key=lambda result: result.person.birthdate if hasattr(result, 'person') and hasattr(result.person, 'birthdate') else large_date ) 
0
source share

Perhaps a monad in Python might be useful here:

 from datetime import datetime def key(result, default=datetime.max): try: return result.person.birthday or default except AttributeError: return default results.sort(key=key) 
0
source share

Extract a list in which items have None keys and add them to the sorted list.

 haystack = [x for x in haystack if x[date_key] is None] + sorted([x for x in haystack if x[date_key] is None], key=lambda x: x[date_key]) 
0
source share

All Articles