CODINGTHOUGHTS

A blog about C#, Python, Azure and full stack development

Sort a List of Dictionaries by a Specific Key in Python

Python, with its rich set of built-in functions and libraries, offers many ways to handle and manipulate data. One common task that developers often encounter is sorting a list of dictionaries by a specific key. In this blog post, we’ll look into how to accomplish this task.

Understanding the Problem

Imagine you have a list of students with their names and ages:

students = [
    {"name": "Dan", "age": 25},
    {"name": "Bob", "age": 20},
    {"name": "Greg", "age": 23},
    {"name": "Sue", "age": 22}
]

Now, let’s say you want to sort this list by age. How would you go about it?

The sorted() Function

Python provides a built-in function called sorted() that can sort any iterable. By default, sorted() will sort a list of dictionaries based on the first key (alphabetically). However, for our use case, we need to specify that we want to sort by the “age” key.

Using a Custom Sorting Key

To sort by the “age” key, we can use a lambda function as the key argument for the sorted() function:

sorted_students = sorted(students, key=lambda x: x['age'])
print(sorted_students)

This will output:

[
    {"name": "Bob", "age": 20},
    {"name": "Sue", "age": 22},
    {"name": "Greg", "age": 23},
    {"name": "Dan", "age": 25}
]

The lambda function takes each dictionary from the list and returns the value of the “age” key. The sorted() function then uses these values to sort the list of dictionaries.

Sorting in Descending Order

If you want to sort the list in descending order, you can use the reverse argument:

sorted_students_desc = sorted(students, key=lambda x: x['age'], reverse=True)
print(sorted_students_desc)

Why Use Lambda?

Lambda functions are small, anonymous functions that can have any number of arguments but only one expression. Their concise nature makes them perfect for short operations like the one we’re performing. However, if your sorting logic becomes more complex, you might consider defining a separate function and passing that as the key argument.

Performance Considerations

The sorted() function is stable, which means that if two items have the same key, their original order will be preserved. This is especially useful when you have multiple criteria for sorting. The time complexity of the sorted() function is O(n log n), making it efficient for large lists.


Posted

in

by

Tags: