PYTHON
Sort a List of Custom Objects by Multiple Attributes in Python
Master sorting complex Python lists containing custom objects or dictionaries by defining multiple sorting criteria, including ascending and descending order.
import operator
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
def __repr__(self):
return f"Person('{self.name}', {self.age}, '{self.city}')"
people = [
Person('Alice', 30, 'New York'),
Person('Bob', 25, 'London'),
Person('Charlie', 30, 'London'),
Person('David', 25, 'New York'),
Person('Eve', 35, 'Paris'),
]
# Sort by age (primary) ascending, then by name (secondary) ascending
sorted_by_age_name = sorted(people, key=lambda p: (p.age, p.name))
print(f"Sorted by Age then Name: {sorted_by_age_name}")
# Sort by city (primary) ascending, then by age (secondary) descending
# Use operator.attrgetter for potentially better performance/readability
sorted_by_city_age = sorted(
people,
key=lambda p: (p.city, -p.age) # Negative age for descending numerical sort
)
print(f"
Sorted by City then Age (desc): {sorted_by_city_age}")
How it works: When sorting a list of custom objects or dictionaries by multiple criteria, Python's `sorted()` function (or list's `sort()` method) with a `key` argument is incredibly powerful. By providing a `lambda` function or `operator.attrgetter` (for objects) that returns a tuple of the attributes, Python will sort based on the first element of the tuple, then the second if the first elements are equal, and so on. To achieve descending order for a numerical attribute within a tuple sort, you can simply negate the value (e.g., `-p.age`).