Sort a list of objects based on an attribute of the objects in Python


Python tip:

You can use attrgetter to sort a list of objects based on the value of the selected attribute.

An Example👇

from operator import attrgetter


class User:
    def __init__(self, username):
        self.username = username

    def __repr__(self):
        return f'User(username="{self.username}")'


users = [User("johndoe"), User("bobby"), User("marry")]

print(sorted(users, key=attrgetter("username")))
# => [User(username="bobby"), User(username="johndoe"), User(username="marry")]