Sort a list of objects by an attribute / function value
You have a list of objects that you would like to sort by an attribute.
import operator countries.sort(key=operator.attrgetter("population"), reverse=False)
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.
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
import operator # students is a list of Student objects students.sort(key=operator.methodcaller("get_avg_grade"), reverse=False)