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

Better Stack Team
Updated on January 26, 2023

In Python, you can use the sorted() function to sort a list of dictionaries by a specific value of the dictionary. The sorted() function takes two arguments: the list to be sorted, and a key function that maps each element of the list to a value that is used for sorting.

For example, if you have a list of dictionaries called my_list, and you want to sort it by the value of the 'age' key of each dictionary, you can use the following code:

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

You can also use the itemgetter() function from the operator module as the key function, which is more efficient than using a lambda function:

 
from operator import itemgetter
sorted_list = sorted(my_list, key=itemgetter('age'))

If you want to sort the list in descending order, you can pass the reverse=True argument to the sorted() function:

 
sorted_list = sorted(my_list, key=lambda x: x['age'], reverse=True)
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →