Sorting by Multiple Fields in Python
Posted by Aly Sivji in Quick Hits
A couple of weeks ago, I stumbled across the Python Sorting HOW TO. Learned that Python can sort objects by multiple attributes using operator.attrgetter
and operator.itemgetter
.
In this Quick Hit, I will show the Pythonic way of sorting objects by multiple attributes.
Note: This example is leveraging Python 3.7 dataclasses for convenience. Objects can be of any type.
from dataclasses import dataclass
import operator
import random
import sys
from faker import Faker
fake = Faker()
sys.version_info
# Create employees to sort
@dataclass(order=True)
class Employee:
name: str
age: int
title: str
employees = []
for idx in range(10):
_name = fake.name()
_title = fake.profile(fields="job")["job"]
_age = random.randint(18, 55)
employee = Employee(name=_name, title=_title, age=_age)
employees.append(employee)
employees
sorted(employees)
sorted(employees, key=operator.attrgetter("age"))
sorted(employees, key=operator.attrgetter("age", "name"))
Notice the employees are sorted by age and by name.
Comments