• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Sort by Two Keys in Python

Sort by Two Keys in Python

July 11, 2022 Leave a Comment

To sort a list of objects by two keys in Python, the easiest way is with the key parameter and a tuple of the keys you want to sort by.

list_of_dicts = [{"name":"Bob","weight":100,"height":50},
{"name":"Sally","weight":120,"height":70},
{"name":"Jim","weight":120,"height":60},
{"name":"Larry","weight":150,"height":60}]

list_of_dicts.sort(key= lambda x: (x["weight"],x["name"]))

print(list_of_dicts)

#Output:
[{'name': 'Bob', 'weight': 100, 'height': 50}, {'name': 'Jim', 'weight': 120, 'height': 60}, {'name': 'Sally', 'weight': 120, 'height': 70}, {'name': 'Larry', 'weight': 150, 'height': 60}]

The Python sort() and sorted() functions allow us to sort collections of data.

One such situation where we need to do a little more work to get the result we want is if we want to sort our data by two keys.

To sort a list of objects by two keys in Python, the easiest way is with the key parameter and a tuple of the keys you want to sort by.

Just pass the keys you want to sort by as a tuple for your sorting lambda expression.

Below is a simple example showing you how to sort a list of dictionaries by two keys in Python.

list_of_dicts = [{"name":"Bob","weight":100,"height":50},
{"name":"Sally","weight":120,"height":70},
{"name":"Jim","weight":120,"height":60},
{"name":"Larry","weight":150,"height":60}]

list_of_dicts.sort(key= lambda x: (x["weight"],x["name"]))

print(list_of_dicts)

#Output:
[{'name': 'Bob', 'weight': 100, 'height': 50}, {'name': 'Jim', 'weight': 120, 'height': 60}, {'name': 'Sally', 'weight': 120, 'height': 70}, {'name': 'Larry', 'weight': 150, 'height': 60}]

You can achieve the same result with the sorted() function as well.

list_of_dicts = [{"name":"Bob","weight":100,"height":50},
{"name":"Sally","weight":120,"height":70},
{"name":"Jim","weight":120,"height":60},
{"name":"Larry","weight":150,"height":60}]

sorted_list_of_dicts = sorted(list_of_dict, key= lambda x: (x["weight"],x["name"]))

print(sorted_list_of_dicts)

#Output:
[{'name': 'Bob', 'weight': 100, 'height': 50}, {'name': 'Jim', 'weight': 120, 'height': 60}, {'name': 'Sally', 'weight': 120, 'height': 70}, {'name': 'Larry', 'weight': 150, 'height': 60}]

Sorting List of Tuples by Two Keys in Python

If you have a list of tuples and want to sort these tuples, you can take the example from above and modify it slightly.

To sort a list of tuples by the first and second element, for example, you will pass the first and second element for your tuple to the lambda function.

Below is an example of how you can sort a list of tuples by two keys in Python.

list_of_tuples= [(3, 5, 9),(1, 2, 3),(2, 5, 7),(1, 2, 4),(2, 3, 6)]

list_of_tuples.sort(key= lambda x: (x[0],x[1]))

print(list_of_tuples)

#Output:
[(1, 2, 3), (1, 2, 4), (2, 3, 6), (2, 5, 7), (3, 5, 9)]

Hopefully this article has been useful for you to learn how to sort a list of objects by two keys in Python.

Other Articles You'll Also Like:

  • 1.  How to Slice a Dictionary in Python
  • 2.  Python Replace Space with Underscore Using String replace() Function
  • 3.  Count Unique Values in pandas DataFrame
  • 4.  Using Python to Count Number of True in List
  • 5.  Get Elapsed Time in Seconds in Python
  • 6.  Find Least Common Multiple of Numbers Using Python
  • 7.  Calculate Compound Interest in Python
  • 8.  Using Python to Insert Item Into List
  • 9.  Using Python to Convert Integer to String with Leading Zeros
  • 10.  Python Check if Object is Iterable with hasattr() Function

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy