Skip to main content

How to Sort Objects by a Custom Property in Python


How to Sort Objects by a Custom Property in Python

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 = 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")
	# Display the dates and titles
	print("Unsorted Date from obj1: " +str( + " with title: " +obj1.title)
	print("Unsorted Date from obj2: " +str( + " with title: " +obj2.title)
	print("Unsorted Date from obj3: " +str( + " with title: " +obj3.title)
	print("Unsorted Date from obj4: " +str( + " with title: " +obj4.title)
	print("Unsorted Date from obj5: " +str( + " 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:
# The value for the key param needs to be a value that identifies the sorting property on the object
customObjects.sort(key=lambda x:, reverse=True)
for obj in customObjects:
	print("Sorted Date from obj: " +str( + " 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!

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.