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

πŸ’‘ Problem Formulation: Developers often encounter a need to sort a list of dictionaries – a data structure used to store collections of key-value pairs. The challenge is to arrange the dictionaries based on the value associated with a specific key. For example, given a list of dictionaries representing products with keys ‘name’ and ‘price’, the goal may be to sort the products by ascending or descending price.

Method 1: Using the sorted() Function with a Lambda Expression

The sorted() function in Python, coupled with a lambda expression, provides a concise way to sort a list of dictionaries by the value of a specific key. By passing a lambda function to the key argument of sorted(), you can specify the dictionary’s key to sort on.

Here’s an example:

products = [
    {'name': 'apple', 'price': 0.95},
    {'name': 'banana', 'price': 0.50},
    {'name': 'cherry', 'price': 3.05}
]
sorted_products = sorted(products, key=lambda x: x['price'])

Output:

[
    {'name': 'banana', 'price': 0.50},
    {'name': 'apple', 'price': 0.95},
    {'name': 'cherry', 'price': 3.05}
]

In the presented code snippet, sorted() utilizes a lambda function that takes an element x (a dictionary) and returns the value associated with the key ‘price’. This sorts the list of dictionaries in ascending order based on their price.

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

The list.sort() method sorts the list in place. By providing a function to the key parameter, you can control the sort order based on the values of a specified key in the dictionaries. This is efficient as it does not create a new list.

Here’s an example:

products.sort(key=lambda x: x['price'])

Output:

[
    {'name': 'banana', 'price': 0.50},
    {'name': 'apple', 'price': 0.95},
    {'name': 'cherry', 'price': 3.05}
]

This code modifies the original products list by sorting the dictionaries based on the ‘price’ key. The lambda function once again helps in determining the values used for sorting.

Method 3: Using the Operator Module

The operator module provides a way to access the itemgetter function, which can be used to create a callable that accesses a dictionary’s key. When used with sorted(), it can be more readable and faster than a lambda expression.

Here’s an example:

from operator import itemgetter
sorted_products = sorted(products, key=itemgetter('price'))

Output:

[
    {'name': 'banana', 'price': 0.50},
    {'name': 'apple', 'price': 0.95},
    {'name': 'cherry', 'price': 3.05}
]

Using itemgetter('price') efficiently grabs the ‘price’ value from each dictionary for sorting, often providing better performance compared to a lambda function.

Method 4: Custom Sort Function

For complex sorting logic, you can define a custom sort function. This allows for sorting the dictionaries by multiple keys or any complex criteria. The custom function is passed to the key argument of the sorted() function.

Here’s an example:

def get_price(item):
    return item['price']

sorted_products = sorted(products, key=get_price)

Output:

[
    {'name': 'banana', 'price': 0.50},
    {'name': 'apple', 'price': 0.95},
    {'name': 'cherry', 'price': 3.05}
]

This code defines a custom function get_price that extracts the ‘price’ key from a dictionary. The function is then used as the sorting key. This method separates the sorting logic for readability and reusability.

Bonus One-Liner Method 5: Using a List Comprehension

A one-liner approach using list comprehension can be particularly elegant. Although less readable for beginners, it provides an inline method to create a new sorted list by specifying the sort key right in the comprehension.

Here’s an example:

sorted_products = [dict(t) for t in sorted((d['price'], d) for d in products)]

Output:

[
    {'price': 0.50, 'name': 'banana'},
    {'price': 0.95, 'name': 'apple'},
    {'price': 3.05, 'name': 'cherry'}
]

This list comprehension creates tuples with the ‘price’ as the first item and the entire dictionary as the second. Sorting these tuples naturally sorts by the price, and then reconstructs dictionaries in the sorted order.

Summary/Discussion

  • Method 1: Using sorted() with Lambda. Quick and concise. Not as readable for complex sorting logic.
  • Method 2: In-Place Sorting with list.sort(). Efficient as it does not create a new list. Alters the original list.
  • Method 3: Using the Operator Module. Can be faster than a lambda expression. Improves code readability.
  • Method 4: Custom Sort Function. Allows for complex sorting logic. Enhances readability and is reusable.
  • Bonus Method 5: List Comprehension. Offers an elegant one-liner. Can be obscure for those not familiar with comprehensions.