Post Image

Python Sort List of Objects by Object Attribute

If you have a list of objects in Python that you want to sort, lets say by a name attribute this can be easily accomplished in a single line of code using the sorted method that is built into Python

 

Object

Below I have an example object defined.

class Person:
    def __init__(self, first, last):
        self.first_name = first
        self.last_name = last

We can see this is a representation of a person and it has  first_name and last_name attributes.

 

If I have a list of instances of this object

p1 = Person('Randy', 'Jackson')
p2 = Person ('Tom', 'Morello')
p3 = Person('Elton', 'John')

unsorted_list = [p1, p2, p3]

In their current state, these objects are unsorted

for person in unsorted_list:
    print(person.first_name, person.last_name)
$
Randy Jackson
Tom Morello
Elton John
$

 

Sorting the Unordered List

So to sort these objects we can use this code

sorted_list = sorted(unsorted_list, key=lambda x: getattr(x, 'first_name'), reverse=False)

We are sorting the list by the first_name attribute

We set reverse to False so it orders A - Z

This creates a new list that is sorted

After we create a new list that is a copy of the first but sorted, we can iterate over it to show it is in the proper order.

for person in sorted_list:
    print(person.first_name, person.last_name)
$
Elton John
Randy Jackson
Tom Morello
$

 

Making it Reusable

While you can paste this code in and modify the attributes I find it is more convenient to abstract it away in a function that I can just call. 

def sort_objects(objects, attribute, reverse=False):
    return sorted(objects, key=lambda x: getattr(x, attribute), reverse=reverse)

This function takes the object list and string representation of attribute to order by as required arguments.

It also takes the order reverse as an optional argument that is set to False by default.

 

 



Comments (0)
Leave a Comment