5 Best Ways to Sort a List of Dictionaries by Values in Python Using Lambda Functions

πŸ’‘ Problem Formulation: Suppose you’re working with a list of dictionaries in Python, and you need to sort this list based on the value of one of the keys in the dictionaries. For example, if you have the input [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}], you may want to sort it by the age key, resulting in the output [{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]. The lambda function in Python can provide a concise way to do this.

Method 1: Using the sorted() Function

The sorted() function returns a new sorted list from the items in an iterable. By passing a lambda function as the key argument, you can sort a list of dictionaries based on any key value in an elegant and readable manner.

Here’s an example:

my_list = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}]
sorted_list = sorted(my_list, key=lambda item: item['age'])
print(sorted_list)

The output of this code snippet:

[{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]

This code snippet uses a lambda function to extract the value associated with the key ‘age’ from each dictionary. The sorted() function then sorts the list of dictionaries based on these values in ascending order.

Method 2: Sorting In-Place With list.sort()

The list.sort() method sorts a list in place, modifying the original list. Like with sorted(), a lambda function can be used as the key to sort by dictionary values.

Here’s an example:

my_list = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}]
my_list.sort(key=lambda item: item['age'])
print(my_list)

The output of this code snippet:

[{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]

This code modifies the original list directly. The lambda function provided to the key parameter of the list.sort() method guides the sorting, based on each dictionary’s ‘age’ value.

Method 3: Using Lambda for Reverse Sorting

To sort the list in descending order, you can pass reverse=True to the sorted() or list.sort() functions in combination with the lambda function.

Here’s an example:

my_list = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}]
sorted_list = sorted(my_list, key=lambda item: item['age'], reverse=True)
print(sorted_list)

The output of this code snippet:

[{'name': 'Bob', 'age': 30}, {'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 20}]

The lambda function is the same as in previous methods, but setting reverse=True sorts the dictionaries by the age key in descending order.

Method 4: Sorting by Multiple Keys

We can use lambda functions to sort by multiple keys by returning a tuple from the lambda function, which the sorted() or list.sort() functions will use to sort the dictionaries.

Here’s an example:

my_list = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 20}]
sorted_list = sorted(my_list, key=lambda item: (item['age'], item['name']))
print(sorted_list)

The output of this code snippet:

[{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 25}]

This code snippet first sorts the list of dictionaries by age and then by name, as the lambda function returns a tuple consisting of the age and name. When ages are the same, the dictionaries are further sorted by the name.

Bonus One-Liner Method 5: Complex Sorting With a Single Lambda

For complex sorting that involves conditionals or more logic, a single lambda can encapsulate this. Although it might not always be the most readable, it is powerful.

Here’s an example:

my_list = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 20}]
sorted_list = sorted(my_list, key=lambda item: (item['age'], -len(item['name'])))
print(sorted_list)

The output of this code snippet:

[{'name': 'Charlie', 'age': 20}, {'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 25}]

This snippet sorts by age, then by name length in descending order without separate lambda functions or additional parameters in the sorted() call.

Summary/Discussion

  • Method 1: Using sorted() Function. It is simple, does not modify the original list, and is generally preferred for readability. However, it creates a new list, consuming more memory.
  • Method 2: Sorting In-Place With list.sort(). Efficient as it does not create a new list, ideal for large data sets. Alters the original list, which may not be desired in all cases.
  • Method 3: Using Lambda for Reverse Sorting. Simple extension of previous methods to handle descending sorts. Can be less intuitive for those unfamiliar with the reverse parameter.
  • Method 4: Sorting by Multiple Keys. Extremely flexible, allowing for complex sorting. Can become hard to read with many sorting keys.
  • Bonus Method 5: Complex Sorting With a Single Lambda. Good for one-off complex conditions, but can compromise readability and maintainability.