How do I sort a list of dictionaries by a value of the dictionary?

To sort a list of dictionaries by a value of the dictionary, you can use the sorted() function and specify the key parameter to be a lambda function that returns the value you want to sort by.

Here is an example:

data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Eve', 'age': 20}]

sorted_data = sorted(data, key=lambda x: x['age'])

print(sorted_data)

The output will be:

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

Watch a course Python - The Practical Guide

This sorts the list of dictionaries in ascending order based on the value of the 'age' key. You can also use the reverse parameter of the sorted() function to sort the list in descending order.

data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Eve', 'age': 20}]

sorted_data = sorted(data, key=lambda x: x['age'], reverse=True)

print(sorted_data)

The output will be:

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