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

πŸ’‘ Problem Formulation: When working with lists of dictionaries in Python, a common task is to sort the list based on the value of one of the attributes within the dictionaries. Suppose we have a list of dictionaries where each dictionary represents a person, with attributes “name” and “age”. The goal is to sort this list by the “age” attribute in ascending order.

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

This method involves using the built-in sorted() function and a lambda expression to sort the list. The lambda function extracts the attribute you want to sort by (e.g., “age”) from each dictionary. This method is quick and easy for simple sorting tasks, and you can reverse the order by setting the reverse parameter to True.

Here’s an example:

people = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 22}, {'name': 'Dave', 'age': 30}]
sorted_people = sorted(people, key=lambda x: x['age'])
print(sorted_people)

Output of the code snippet:

[{'name': 'Jane', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Dave', 'age': 30}]

This code snippet creates a list of dictionaries representing people, with “name” and “age” attributes. It uses the sorted() function with a lambda function as the key to sort the list of dictionaries by the “age” attribute. The resulting list is sorted in ascending order of age.

Method 2: Using the operator Module

For better readability and performance, especially in larger scripts, we can use the itemgetter function from the operator module to achieve the same result as a lambda expression. This approach is more readable to those familiar with the operator module.

Here’s an example:

from operator import itemgetter

people = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 22}, {'name': 'Dave', 'age': 30}]
sorted_people = sorted(people, key=itemgetter('age'))
print(sorted_people)

Output of the code snippet:

[{'name': 'Jane', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Dave', 'age': 30}]

The given code example sorts the list of dictionaries using the itemgetter function from the operator module. This method enhances readability and may offer improved performance over the lambda approach, making it a solid alternative for sorting lists of dictionaries by an attribute.

Method 3: Using a Custom Sort Function

If you seek more control or wish to add complex sorting logic, defining a custom function is useful. The custom function can then be passed to the sorted() function as the key argument. This approach provides a clear separation of the sorting logic, making the code cleaner.

Here’s an example:

def get_age(person):
    return person['age']

people = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 22}, {'name': 'Dave', 'age': 30}]
sorted_people = sorted(people, key=get_age)
print(sorted_people)

Output of the code snippet:

[{'name': 'Jane', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Dave', 'age': 30}]

Here, a custom function get_age() is defined for extract the age from a dictionary. This function helps to decouple the sorting logic from the data structure and provides flexibility for more complex sorting operations.

Method 4: Using the sort() Method with a Comparison Function

The sort() method of the list object can also be used to sort the list in place. While it has the disadvantage of modifying the original list, it can be a bit more efficient memory-wise because it doesn’t need to create a copy of the list.

Here’s an example:

people = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 22}, {'name': 'Dave', 'age': 30}]
people.sort(key=lambda x: x['age'])
print(people)

Output of the code snippet:

[{'name': 'Jane', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Dave', 'age': 30}]

This method sorts the list in place utilizing a lambda function to determine the sorting mechanism. This approach is memory efficient but alters the original list, which might not always be desired.

Bonus One-Liner Method 5: Using List Comprehensions and Sorted

List comprehensions combined with the sorted() function provide a concise way to create a new, sorted list. This one-liner method is Pythonic and can be quite readable for those well-versed in list comprehensions.

Here’s an example:

people = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 22}, {'name': 'Dave', 'age': 30}]
sorted_people = [person for person in sorted(people, key=lambda x: x['age'])]
print(sorted_people)

Output of the code snippet:

[{'name': 'Jane', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Dave', 'age': 30}]

This concise snippet sorts the list of dictionaries within a list comprehension. The resulting sorted list is new and does not alter the original list.

Summary/Discussion

  • Method 1: Sorted with Lambda. Straightforward and quick. Not as performant for very complex sorting logic.
  • Method 2: Operator Module. More readable to those familiar with Python standard libraries. Slight performance improvement over lambda.
  • Method 3: Custom Sort Function. Great for complex sorting logic and cleaner code structure. Slightly more verbose.
  • Method 4: In-Place sort. Efficient with memory as no copy of the list is created. The original list is modified.
  • Bonus Method 5: List Comprehension. Pythonic and readable one-liner but might be less clear to Python beginners.