Python sorted() Function
You can optionally specify parameters for sort customization like sorting order and sorting criteria.
Syntax
sorted ( iterable , key , reverse )
The method has two optional arguments, which must be specified as keyword arguments.
Parameter | Condition | Description |
iterable | Required | Any iterable (list, tuple, dictionary, set etc.) to sort. |
key | Optional | A function to specify the sorting criteria. Default value is None. |
reverse | Optional | Settting it to True sorts the list in reverse order. Default value is False. |
Return Value
The method returns a new sorted list from the items in iterable .
Sort Iterables
sorted() function accepts any iterable like list, tuple, dictionary, set, string etc.
# strings are sorted alphabetically L = ['red', 'green', 'blue', 'orange'] x = sorted(L) print(x) # Prints ['blue', 'green', 'orange', 'red'] # numbers are sorted numerically L = [42, 99, 1, 12] x = sorted(L) print(x) # Prints [1, 12, 42, 99]
If you want to sort the list in-place, use built-in sort() method.
sort() is actually faster than sorted() as it doesn’t need to create a new list.
# Sort a tuple L = ('cc', 'aa', 'dd', 'bb') x = sorted(L) print(x) # Prints ['aa', 'bb', 'cc', 'dd']
sorted() function sorts a dictionary by keys, by default.
D = 'Bob':30, 'Sam':25, 'Max':35, 'Tom':20> x = sorted(D) print(x) # Prints ['Bob', 'Max', 'Sam', 'Tom']
To sort a dictionary by values use the sorted() function along with the values() method.
D = 'Bob':30, 'Sam':25, 'Max':35, 'Tom':20> x = sorted(D.values()) print(x) # Prints [20, 25, 30, 35]
Sort in Reverse Order
You can also sort an iterable in reverse order by setting reverse to true.
L = ['cc', 'aa', 'dd', 'bb'] x = sorted(L, reverse=True) print(x) # Prints ['dd', 'cc', 'bb', 'aa']
Sort with Key
Use key parameter for more complex custom sorting. A key parameter specifies a function to be executed on each list item before making comparisons.
For example, with a list of strings, specifying key=len (the built-in len() function) sorts the strings by length, from shortest to longest.
L = ['orange', 'red', 'green', 'blue'] x = sorted(L, key=len) print(x) # Prints ['red', 'blue', 'green', 'orange']
Sort with Custom Function
You can also pass in your own custom function as the key function. A key function should take a single argument and return a key to use for sorting.
# Sort by the age of students def myFunc(e): return e[1] # return age L = [('Sam', 35), ('Max', 25), ('Bob', 30)] x = sorted(L, key=myFunc) print(x) # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
Sort with lambda
A key function may also be created with the lambda expression. It allows us to in-line function definition.
# Sort by the age of students L = [('Sam', 35), ('Max', 25), ('Bob', 30)] x = sorted(L, key=lambda student: student[1]) print(x) # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
Sort with Operator Module Functions
To access items of an iterable , Python provides convenience functions like itemgetter() and attrgetter() from operator module.
# Sort by the age of students from operator import itemgetter L = [('Sam', 35), ('Max', 25), ('Bob', 30)] x = sorted(L, key=itemgetter(1)) print(x) # Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]
Multiple Level Sorting
The operator module functions allow multiple levels of sorting as well.
# Sort by grade then by age from operator import itemgetter L = [('Bob', 'B', 30), ('Sam', 'A', 35), ('Max', 'B', 25), ('Tom', 'A', 20), ('Ron', 'A', 40), ('Ben', 'B', 15)] x = sorted(L, key=itemgetter(1,2)) print(x) # Prints [('Tom', 'A', 20), # ('Sam', 'A', 35), # ('Ron', 'A', 40), # ('Ben', 'B', 15), # ('Max', 'B', 25), # ('Bob', 'B', 30)]
Sort Custom Objects
Let’s create a list of custom objects.
# Custom class class Student: def __init__(self, name, grade, age): self.name = name self.grade = grade self.age = age def __repr__(self): return repr((self.name, self.grade, self.age)) # a list of custom objects L = [Student('Bob', 'B', 30), Student('Sam', 'A', 35), Student('Max', 'B', 25)]
Here are some techniques to sort a list of custom objects.
# with lambda x = sorted(L, key=lambda student: student.age) print(x) # [('Max', 'B', 25), ('Bob', 'B', 30), ('Sam', 'A', 35)]
# with attrgetter from operator import attrgetter x = sorted(L, key=attrgetter('age')) print(x) # [('Max', 'B', 25), ('Bob', 'B', 30), ('Sam', 'A', 35)]
# Custom Objects - Multiple Level Sorting # Sort by grade then by age x = sorted(L, key=attrgetter('grade', 'age')) print(x) # [('Sam', 'A', 35), ('Max', 'B', 25), ('Bob', 'B', 30)]
How to Sort Objects by a Custom Property in Python
Submitted by matt_eaton on Sat, 01/27/2018 — 01:04 PM
Tags
If you are like me and sometimes you forget the syntax on how to sort a list of custom objects by property then this tutorial is for you. It seems like there is always a need to sort and manipulate custom objects by property and that was my why I wanted to write this tutorial. To demonstrate how to take a custom list of objects and sort those objects by a specific property. In the case of this tutorial I have chosen to use a date property because sorting by date is a very real world example of something you may run into in the work place, but the same code would also work for numbers or strings as well. By the end of this tutorial you should know how to sort a custom list of objects by any specific property of that object.
NOTE: This tutorial was tested with Python 2 and 3 on a macOS and Linux operating system. Windows was not tested, but running this tutorial in a Windows subsystem should produce the same results. Please let me know if it does not. 👍
Setup the Basics 👨💻
Below what I want to do is set the stage for a real world situation that you may encounter when working with Python. I created a very basic custom object to represent articles found on this blog. This custom object contains a title and a date property. Below the custom object in the main function I created five custom objects each with a date and a title in random order. For display purposes I then print out each of the objects to show that it is not in any sort of order.
# Custom object to hold article date and time class customObject(): def __init__(self, title, date): self.title = title self.date = datetime.strptime(date, "%B %d, %Y") def main(): obj3 = customObject("TLS 1.3 - Better, Stronger, Faster", "January 6, 2018") obj4 = customObject("User Interface Testing with Swift and XCTest", "December 10, 2017") obj2 = customObject("How to Use Python List Comprehensions", "December 2, 2017") obj1 = customObject("Attending WWDC 2017 - Predictions Answered", "June 13, 2017") obj5 = customObject("Swift Network Testing - Automate XCTest with Python", "November 26, 2017") print("---------------------------------------------------------------") # Display the dates and titles print("Unsorted Date from obj1: " +str(obj1.date) + " with title: " +obj1.title) print("Unsorted Date from obj2: " +str(obj2.date) + " with title: " +obj2.title) print("Unsorted Date from obj3: " +str(obj3.date) + " with title: " +obj3.title) print("Unsorted Date from obj4: " +str(obj4.date) + " with title: " +obj4.title) print("Unsorted Date from obj5: " +str(obj5.date) + " with title: " +obj5.title +"\n")
Sorting the Objects 🎉
Now for the fun part. In the real world you will probably encounter a situation where you will need to sort a data structure or a list by property. So I took my unsorted objects and added them to a list — out of order. From here I used the Python sort method to sort my list by date property in descending order using the optional key and reverse parameters. From here I used a for loop and printed out the newly sorted list to display the successful sort of my list.
So how does this apply to sorting custom objects by property? Well, the sort method I used in this example can be used to sort any collection of like objects by property. For example, if you take a look at the key parameter you will see that I used an inline lambda function as the argument and specified the date on customObject, but this could have just as easily been the title property too. The key parameter is used to identify the items to sort the objects on. Next you will see that I input a true argument to the reverse parameter. This is to let the sort method know that I want to sort these objects descending. And that is all there is to it. These technique could be used with numeric or string values also, not just dates. It is highly flexibly and very valuable to incorporate in your development toolbox.
customObjects = [obj1, obj2, obj3, obj4, obj5] # One line sort function method using an inline lambda function lambda x: x.date # The value for the key param needs to be a value that identifies the sorting property on the object customObjects.sort(key=lambda x: x.date, reverse=True) for obj in customObjects: print("Sorted Date from obj: " +str(obj.date) + " with title: " +obj.title)
In Summary ⌛️
Now you know more about how to sort objects by custom property in Python! Please feel free to download the code example from my Github and mess around with it. Please let me know if you have any questions, comments, or concerns and please feel free to take a look at other tutorials on this website.
Thank you very much for reading!
Credits: Cover image designed by Freepik.
Member for
Long time mobile team lead with a love for network engineering, security, IoT, oss, writing, wireless, and mobile. Avid runner and determined health nut living in the greater Chicagoland area.