45

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?

shane
  • 1,025
  • 2
  • 11
  • 9

2 Answers2

81
results.sort(key=lambda r: r.person.birthdate)
Amber
  • 507,862
  • 82
  • 626
  • 550
16

Totally agree with Amber, but there is another way of sorting by attribute (from the wiki: https://wiki.python.org/moin/HowTo/Sorting):

from operator import attrgetter
sorted_list = sorted(results, key=attrgetter('person.birthdate'))

This method can actually be even faster than sorting with lambda

yentsun
  • 2,488
  • 27
  • 36
  • 3
    `attrgetter()` is convenient if `'person.birdate' is passed as a variable. Otherwise the `lambda` is more flexible (e.g., what if `person` is None sometimes) and the time difference should be negligible in most cases. – jfs Oct 12 '14 at 16:57
  • @J.F. Sebastian: agreed, I just quoted the wiki:) I'll edit the answer – yentsun Oct 20 '14 at 13:04