Python
sort
dictionaries
list
tutorial

How can I sort a list of dictionaries by a value of the dictionary in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

When working with lists of dictionaries in Python, there may be cases where you need to sort the list based on a specific value in the dictionaries. This can be efficiently accomplished using Python's built-in functionalities. Throughout this article, we will explore how to sort a list of dictionaries by a specific value with explanations and examples to make the process clear and straightforward.

Understanding Dictionaries and Lists in Python

Dictionaries

Dictionaries in Python are collections of key-value pairs. Each key in a dictionary is unique, and values can be of any data type.

Example dictionary:

python
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}

Lists of Dictionaries

A list in Python is an ordered collection of items, which can be of any data type, including dictionaries.

Example list of dictionaries:

python
1people = [
2    {'name': 'Alice', 'age': 30},
3    {'name': 'Bob', 'age': 25},
4    {'name': 'Charlie', 'age': 35}
5]

Sorting a List of Dictionaries

Python provides a convenient and efficient way to sort lists, including lists of dictionaries, using functions such as sorted() and the list method .sort().

Using sorted() Function

The sorted() function returns a new sorted list from the original list and does not modify the original list. It takes an iterable as its first argument and can use an optional key parameter to specify a function to execute on each element before comparing the elements.

Example: Sorting by Age

Suppose we want to sort the list of dictionaries people by the age key:

python
1sorted_people = sorted(people, key=lambda person: person['age'])
2
3print(sorted_people)
4# Output: [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}]

In this example, a lambda function lambda person: person['age'] is used. It acts as the key function, extracting the age value from each dictionary for comparison during sorting.

Using .sort() Method

The .sort() method is similar to sorted(), but it modifies the list in place and returns None. It also accepts the optional key parameter.

Example: Sorting by Name

To sort the list in place by the name key:

python
1people.sort(key=lambda person: person['name'])
2
3print(people)
4# Output: [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}]

Here, the lambda person: person['name'] function determines the order by extracting the name from each dictionary.

Sorting with Reverse Order

Both sorted() and .sort() methods also accept a reverse parameter which, when set to True, sorts the list in descending order.

Example: Sorting by Age in Descending Order

python
1# Using sorted()
2sorted_people_desc = sorted(people, key=lambda person: person['age'], reverse=True)
3print(sorted_people_desc)
4# Output: [{'name': 'Charlie', 'age': 35}, {'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
5
6# Using .sort()
7people.sort(key=lambda person: person['age'], reverse=True)
8print(people)
9# Output: [{'name': 'Charlie', 'age': 35}, {'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]

Summary of Key Points

The table below summarizes the main techniques and their characteristics for sorting a list of dictionaries:

MethodDescriptionModificationKey ParameterReverse Order
sorted()Returns a new sorted listNoYesYes
.sort()Sorts the list in placeYesYesYes

Additional Details and Tips

  1. Complex Sorting: For more complex sorting criteria, you can define a function instead of using a lambda. The function can return composite keys (tuples) for multi-level sorting.
    Example:
python
1    def sort_criteria(person):
2        return (person['age'], person['name'])
3
4    sorted_people = sorted(people, key=sort_criteria)
  1. Handling Missing Keys: If some dictionaries might not contain the key you want to sort by, you can use the dictionary's get method in the lambda function, providing a default value.
    Example:
python
    sorted_people = sorted(people, key=lambda person: person.get('age', 0))
  1. Improving Readability: For clarity, especially when sorting by keys within nested dictionaries, consider using more verbose sorting functions.

By understanding these basics and leveraging Python's built-in capabilities, you can effectively and efficiently sort lists of dictionaries according to your needs.


Course illustration
Course illustration

All Rights Reserved.