🐶
Python

Sort List of Dictionaries by Value in Python

By Filip on 10/05/2024

Learn how to easily sort a list of dictionaries in Python based on a specific value within each dictionary using the powerful `sorted()` function and lambda expressions.

Sort List of Dictionaries by Value in Python

Table of Contents

Introduction

In Python, sorting a list of dictionaries based on a specific value within each dictionary is a common task. You can achieve this using the sorted() function along with a custom sorting key defined using a lambda function. This approach allows you to specify the criteria for sorting based on the values associated with a particular key in your dictionaries.

Step-by-Step Guide

To sort a list of dictionaries in Python based on a specific value within each dictionary, you can use the sorted() function along with a custom sorting key.

Let's say you have a list of dictionaries called my_list:

my_list = [
    {'name': 'John', 'age': 30},
    {'name': 'Jane', 'age': 25},
    {'name': 'Peter', 'age': 35}
]

To sort this list by the 'age' value in ascending order, you would use the following code:

sorted_list = sorted(my_list, key=lambda item: item['age'])

In this code:

  • sorted(my_list, key= ...) calls the sorted() function on your list. The key parameter is crucial for custom sorting.
  • lambda item: item['age'] is a lambda function that defines the sorting key. It takes each dictionary (item) in the list and returns the value associated with the 'age' key.

The sorted() function uses this returned value to compare dictionaries and sort them accordingly.

For descending order, you can use the reverse=True argument within sorted():

sorted_list = sorted(my_list, key=lambda item: item['age'], reverse=True)

This approach is flexible and can be adapted to sort by any key within your dictionaries. Just replace 'age' with the desired key.

Code Example

The Python code defines a list of dictionaries, where each dictionary represents a person with 'name' and 'age' attributes. It then demonstrates how to sort this list of dictionaries based on the 'age' and 'name' keys in both ascending and descending order using the sorted() function and lambda expressions for custom sorting logic. The sorted results are printed to the console.

my_list = [
    {'name': 'John', 'age': 30},
    {'name': 'Jane', 'age': 25},
    {'name': 'Peter', 'age': 35}
]

# Sort by 'age' in ascending order
sorted_list_ascending = sorted(my_list, key=lambda item: item['age'])
print("Sorted by age (ascending):", sorted_list_ascending)

# Sort by 'age' in descending order
sorted_list_descending = sorted(my_list, key=lambda item: item['age'], reverse=True)
print("Sorted by age (descending):", sorted_list_descending)

# Sort by 'name' in ascending order
sorted_list_name = sorted(my_list, key=lambda item: item['name'])
print("Sorted by name (ascending):", sorted_list_name)

Explanation:

  1. my_list: This is our initial list of dictionaries.
  2. sorted(my_list, key=lambda item: item['age']):
    • sorted(): This function is used to sort the list.
    • key=lambda item: item['age']: This is the crucial part. It defines a lambda function that tells sorted() how to compare the dictionaries.
      • lambda item: creates an anonymous function that takes each dictionary in the list as item.
      • item['age'] accesses the value associated with the 'age' key in each dictionary. sorted() uses this value for comparison.
  3. reverse=True: Adding this argument to sorted() reverses the sorting order to descending.
  4. Printing: The code then prints the sorted lists to demonstrate the results.

This example clearly shows how to sort by different keys ('age' and 'name') and in different orders (ascending and descending).

Additional Notes

  • Importance of key: The key argument within the sorted() function is what makes custom sorting possible. Without it, Python wouldn't know which value within each dictionary to use for comparison.

  • Lambda Functions: Lambda functions are concise ways to define simple functions inline. They are particularly useful as sorting keys because they provide a compact way to specify the sorting logic without needing a separate function definition.

  • Sorting Stability: Python's sorted() function is stable. This means that if two dictionaries have the same value for the sorting key, their original order in the list is preserved.

  • Alternatives to Lambda Functions: While lambda functions are commonly used, you can also use regular named functions as sorting keys. This can be more readable for complex sorting logic.

  • Error Handling: If the key you specify doesn't exist in all dictionaries, you'll get a KeyError. Consider using get() with a default value to handle missing keys gracefully.

  • In-place Sorting: If you want to modify the original list directly instead of creating a new sorted list, you can use the list.sort() method with the same key and reverse arguments.

  • Sorting by Multiple Keys: You can sort by multiple keys by passing a tuple to the key argument. For example: sorted(my_list, key=lambda item: (item['age'], item['name'])) would sort by age first, and then by name within each age group.

  • Performance: For very large lists, using the operator.itemgetter() function as the sorting key can be slightly faster than using a lambda function.

  • Real-World Applications: Sorting dictionaries is frequent in data analysis, processing API responses, working with configuration files, and many other scenarios.

Summary

This article explains how to sort a list of dictionaries in Python based on the values of a specific key within each dictionary.

Key Points:

  • sorted() function: Used for sorting, with the key parameter enabling custom sorting logic.
  • Lambda function: Defines the sorting key by extracting the desired value from each dictionary.
  • Ascending order: The default sorting order.
  • Descending order: Achieved by setting reverse=True in the sorted() function.

Example:

To sort a list of dictionaries called my_list by the 'age' key in ascending order:

sorted_list = sorted(my_list, key=lambda item: item['age'])

Explanation:

  1. sorted(my_list, key= ...): Sorts my_list using a custom sorting key.
  2. lambda item: item['age']: A lambda function that takes each dictionary (item) and returns its 'age' value. This value is used for comparison during sorting.

Customization:

  • To sort by a different key, replace 'age' with the desired key.
  • To sort in descending order, add reverse=True to the sorted() function.

Conclusion

This article provided a comprehensive guide on sorting lists of dictionaries in Python. By leveraging the sorted() function and utilizing lambda functions for custom sorting logic, you can efficiently organize your data based on specific key values within your dictionaries. Remember to adjust the key argument and reverse parameter according to your desired sorting criteria. Whether you're dealing with age, name, or any other key, the techniques outlined here provide a flexible and powerful approach to sorting dictionaries in Python, a common task in various data manipulation scenarios.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait