Python Sort by Two Keys: Beginner’s to Advanced

Python Sort by Two Keys

In Python, sorting data is a routine task, and while sorting by a single key is straightforward, things might get a bit more intricate when sorting by two or more keys. In this blog post, we delve into the ways to achieve Python sorting by two keys seamlessly. Drawing from expert insights shared on Tutorial Tonight and Stack Overflow, we will guide you through this advanced sorting technique step by step. Let’s get started!

Understanding Python Sorting Basics

Before diving into multi-key sorting, it’s important to grasp the basics of Python sorting.

The sorted() Function

Python offers the sorted() function that enables you to sort the elements of a list or any iterable in a specific order – be it ascending or descending.

The sort() Method

Apart from the sorted() function, Python also brings forth the sort() method, which alters the original list, sorting its elements in a defined manner.

Sorting by Multiple Keys: The Concept

In Python, sorting by multiple keys means that you are sorting a list based on two or more criteria. It’s generally performed using a tuple of keys as the key argument in the sorted() function or sort() method.

Why Use Multiple Keys?

Sorting by multiple keys is crucial when you want to sort a dataset based on a primary key and then further refine the sorted list using a secondary key. It ensures a more nuanced and refined sorted list, offering a much clearer data analysis.

How to Sort by Two Keys in Python

To sort by two keys in Python, you use the key argument in your sorting function, providing it with a function that returns a tuple of the values to be sorted. Here, we illustrate the process step by step.

Using itemgetter

The itemgetter function from the operator module can be used to create a callable object that can fetch the value of the keys from the items in your list.

from operator import itemgetter

data = [(‘Alice’, 30, 5.5), (‘Bob’, 30, 5.9), (‘Charlie’, 25, 5.7)]
sorted_data = sorted(data, key=itemgetter(1, 2))

Using Lambda Function

Alternatively, you can use a lambda function to define the keys based on which the list should be sorted.

data = [(‘Alice’, 30, 5.5), (‘Bob’, 30, 5.9), (‘Charlie’, 25, 5.7)]
sorted_data = sorted(data, key=lambda x: (x[1], x[2]))

In both approaches, the list is primarily sorted by the second element of the tuples and then by the third element.

Python Sorted Multiple Keys: Examples

To get a better understanding, let’s delve into a few practical examples illustrating Python sorted by multiple keys.

Example 1: Sorting a List of Tuples

data = [(‘Alice’, 30, 5.5), (‘Bob’, 30, 5.9), (‘Charlie’, 25, 5.7)]
sorted_data = sorted(data, key=lambda x: (x[1], -x[2]))

Here, the list is sorted by age in ascending order and height in descending order.

Example 2: Sorting a List of Dictionaries

data = [{‘name’: ‘Alice’, ‘age’: 30, ‘height’: 5.5}, {‘name’: ‘Bob’, ‘age’: 30, ‘height’: 5.9}, {‘name’: ‘Charlie’, ‘age’: 25, ‘height’: 5.7}]
sorted_data = sorted(data, key=lambda x: (x[‘age’], x[‘height’]))

This time, we sorted a list of dictionaries based on age and height.

FAQs

1. Can I Sort by More than Two Keys?

Yes, you can sort by as many keys as needed by extending the tuple in the key function.

2. What is the Difference Between sort() and sorted()?

While sort() alters the original list, sorted() returns a new list with sorted elements, keeping the original list unaffected.

3. Can I Use Custom Functions as a Key?

Absolutely, you can define your custom function and use it as a key to facilitate more complex sorting logic.

Conclusion

Understanding how to sort by two keys in Python empowers you to manage and analyze data more effectively. By leveraging the potential of Python sorted multiple keys, you can bring sophistication to your data-sorting tasks and perform complex analyses with ease.

Remember, practice is key to mastering any concept. So, get your hands dirty with coding and experiment with multi-key sorting using various datasets and key combinations. If you have further queries, feel free to drop them in the comments section below. Happy coding!

Read More:

1: How to Find N Root of a Number – Python

2: ssl module in Python is not available

3: ValueError: math domain error Python

4: Error: Legacy-Install-Failure

Latest posts by Muhammad Usman Shafique (see all)