Python Sort by Two Keys


Sorting allow us to organize data in a meaningful way. Python provides several built-in functions and methods to sort data efficiently.

Sorting by one key is straightforward, but there are many situations where you need to sort data based on multiple criteria. For example:


    Table of Contents

  1. Sorting in Python
  2. Sorting by Two Keys in Python
  3. Sorting by Multiple Keys
  4. Two Key Sorting Examples
    1. 1. Sorting Dictionaries
    2. 2. Sorting Lists of Dictionaries
  5. Conclusion
  6. Python Sort by Two Keys FAQ

Sorting In Python

Before diving into sorting by two keys, let's understand the basics of sorting in Python.

Python offers a versatile built-in function called sorted() that allows you to sort various data types such as lists, tuples, and dictionaries.

The sorted() function takes an iterable as its argument and returns a new sorted list. It doesn't modify the original list, ensuring data integrity. By default, the sorted() function sorts elements in ascending order.

Let's see how to use the sorted() function to sort a list of integers.

numbers = [5, 2, 3, 1, 4]

# sort the list
sorted_numbers = sorted(numbers)

print(sorted_numbers)

Output:

[1, 2, 3, 4, 5]

Sorting by Two Keys

Above we have seen how to sort a list of integers. Now let's see how to sort a list of tuples by two keys.

Suppose we have a list of tuples containing the name and marks of students.

students = [
  ('John', 90),
  ('Alex', 80),
  ('Bob', 95),
  ('Alice', 85)
]

Now we want to sort this list by marks and then by name. To do this, we need to pass a key function to the sorted() function.

A key function is a function that takes an element as an argument and returns a value based on which the sorting is done.

Let's see how to sort the above list by marks and then by name.

students = [('John', 90), ('Alex', 80), ('Bob', 95), ('Alice', 75)]

# sort the list by marks and then by name
sorted_students = sorted(students, key=lambda x: (x[1], x[0]))

print(sorted_students)

Output:

[
  ('Alice', 75),
  ('Alex', 80),
  ('John', 90),
  ('Bob', 95)
]

Here, we have passed a lambda function as a key function to the sorted() function. The lambda function takes a tuple as an argument and returns a tuple containing marks and name.

Since the sorted() function sorts elements in ascending order by default, the list is sorted by marks in ascending order.

If you want to sort the list by marks in descending order, you can pass reverse=True as an argument to the sorted() function.

students = [('John', 90), ('Alex', 80), ('Bob', 95), ('Alice', 75)]

# sort the list by marks in descending order and then by name
sorted_students = sorted(students, key=lambda x: (x[1], x[0]), reverse=True)

print(sorted_students)

Output:

[
  ('Bob', 95),
  ('John', 90),
  ('Alex', 80),
  ('Alice', 75)
]

Sorting by Multiple Keys

Now let's see how to sort a list of tuples by multiple keys.

Suppose we have a list of tuples containing the name, age, and marks of students.

students = [
  ('John', 20, 90),
  ('Alex', 18, 80),
  ('Bob', 19, 95),
  ('Alice', 20, 75)
]

Now we want to sort this list by age, marks, and then by name. To do this, we need to pass a key function to the sorted() function.

Let's see how to sort the above list by age, marks, and then by name.

students = [
  ('John', 20, 90),
  ('Alex', 18, 80),
  ('Bob', 19, 95),
  ('Alice', 20, 75)
]

# sort the list by age, marks, and then by name
sorted_students = sorted(students, key=lambda x: (x[1], x[2], x[0]))

print(sorted_students)

Output:

[
  ('Alex', 18, 80),
  ('Bob', 19, 95),
  ('Alice', 20, 75),
  ('John', 20, 90)
]

Sorting by Two Keys in Python

Let's now see different variations of sorting by two keys in Python.

1. Sorting Dictionaries

Suppose we have a dictionary containing the name and marks of students.

students = {
  'John': 90,
  'Alex': 80,
  'Bob': 95,
  'Alice': 85
}

Now we want to sort this dictionary by marks and then by name. To do this, we need to pass a key function to the sorted() function.

Let's see how to sort the above dictionary by marks and then by name.

students = {
  'John': 90,
  'Alex': 80,
  'Bob': 95,
  'Alice': 85
}

# sort the dictionary by marks and then by name
sorted_students = sorted(students.items(), key=lambda x: (x[1], x[0]))

print(sorted_students)

Output:

[
  ('Alex', 80),
  ('Alice', 85),
  ('John', 90),
  ('Bob', 95)
]

2. Sorting Lists of Dictionaries

Suppose we have a list of dictionaries containing the computer parts, prices and ratings. Now we want to sort this list by price and then by rating.

products = [
  {'name': 'Keyboard', 'price': 25.99, 'rating': 4.2},
  {'name': 'Mouse', 'price': 15.99, 'rating': 4.5},
  {'name': 'Monitor', 'price': 199.99, 'rating': 4.0},
  {'name': 'Headphones', 'price': 49.99, 'rating': 3.8}
]

# sort the list by price and then by rating
sorted_products = sorted(products, key=lambda x: (x['price'], x['rating']))

print(sorted_products)

Output:

[
  {'name': 'Mouse', 'price': 15.99, 'rating': 4.5},
  {'name': 'Keyboard', 'price': 25.99, 'rating': 4.2},
  {'name': 'Headphones', 'price': 49.99, 'rating': 3.8},
  {'name': 'Monitor', 'price': 199.99, 'rating': 4.0}
]

Conclusion

In this article, we saw how to sort list, dictionary, and list of dictionaries by multiple keys in Python.

We looked at different variations of sorting by multiple keys in Python with examples.

By understanding these concepts, you can efficiently sort data based on multiple attributes in your Python projects.


  1. Can I sort by more than two keys in Python?

    Yes, you can sort by more than two keys in Python. Simply provide a tuple of keys to the key parameter, specifying the desired order of sorting.

  2. How do I specify the order of sorting for each key?

    To specify the order of sorting for each key, you can use the sorted() function with a custom key function. The key function should return a tuple of keys in the desired order.

  3. What happens if the keys have different data types?

    Python's sorting mechanism is flexible and can handle different data types. However, it's important to ensure that the keys are compatible and can be compared correctly.

  4. Is the order of the keys significant in Python sorting?

    Yes, the order of the keys is significant in Python sorting. The sorting process considers the keys in the order they are provided.