Home > python > Sort a list of objects by an attribute / function value

Sort a list of objects by an attribute / function value

Problem
You have a list of objects that you would like to sort by an attribute.

Solution

import operator
countries.sort(key=operator.attrgetter("population"), reverse=False)

Here countries is a list of Country objects. In the Country class there is an attribute called “population“. It will sort the countries in ascending order by the number of population.

Update (20110911)
Of course, you can also sort a list of objects by the value of a function. For instance, you have a class Student and the grades are stored in a list. You want to sort the students by the average of their grades. This value is calculated by the function get_avg_grade().

import operator
# students is a list of Student objects
students.sort(key=operator.methodcaller("get_avg_grade"), reverse=False)

Links
HowTo/Sorting – PythonInfo Wiki

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: