Explain Codes LogoExplain Codes Logo

Sorting a Python list by two fields

python
multiple-field-sorting
custom-sorting-functions
performance-optimization
Alex KataevbyAlex Kataev·Mar 6, 2025
TLDR

Sort a list by two aspects using Python's sorted() function. We form a tuple by combining two fields within the key parameter. Here's the core code snippet:

# Assuming a list of dictionaries data = [{'name': 'John', 'age': 25, 'score': 90}, # John's score is arguable if you ask his professor {'name': 'Doe', 'age': 22, 'score': 95}, # Doe has been practicing 24/7 (Not recommended approach!) {'name': 'Jane', 'age': 25, 'score': 100}] # Jane is simply a genius ;) # Sorting by 'age', followed by 'score' sorted_data = sorted(data, key=lambda x: (x['age'], x['score'])) # Think of it as an exam. Age first, then score!

This will initially sort by age and afterwards by score within each age group. It's sort of like sorting your backup shoes: by size first, then by color!

Breaking down multi-field sorting

Stability: A Sorting Superpower

Python's sorting algorithm is stable—meaning when records share identical keys, their original sequence is preserved. This is particularly useful for multiple field sorting as the original order is maintained unless directly compared.

When Performance Matters

By sorting multiple fields, we inadvertently introduce implications on performance. The choice of lambda and itemgetter can impact this, so profiling your code could be an interesting evening plan.

Custom Functions: The VIP Room for Sorting

Sometimes, our standard sorting logic isn’t enough. In such cases, custom sorting functions can be employed for complex comparison operations including case-insensitive arrangement or dealing with mixed field types.

Reverse Sort: Turning Things Upside Down

To sort in descending order, try reversing sort. But beware—the process isn't as straightforward as it sounds with multiple fields. You need to state the reverse order separately for each field—like a demanding conductor in an orchestra.

Tips for everyday sorting tasks

Sorting just got real(ly complex)

When you step up in the game and deal with complex data structures, like lists of classes or nested dictionaries, your key function needs to be smart enough to navigate and fetch the fields required for sorting.

In-place sort: the .sort() magic

While the sorted() function spawns a new list, the .sort() method is like this cool magician that sorts the list right in its place—perfect for saving memory with large data sets:

# In-place magic with 'list.sort()' data.sort(key=lambda x: (x['age'], x['score'])) # Now, this is eco-friendly and, well, genius!

Sorting: Unboxing the black box

Sort data directly from gifts like CSV files or other external raw sources. Just convert the file to a list of dictionaries or tuples and voila—apply the same multi-field sorting with either sorted() function or .sort() method.