Python sort list of dictionaries | Example code

Use lambda function with sorted() inbuilt function to sort the list of dictionaries in Python. Pass the list containing dictionaries and keys to the sorted method.

Example sort list of dictionaries in Python

Simple example code demonstrates the working of sorted() with lambda. We sort the list of dict by age, age+name, or name.

list1 = [{"name": "Cat", "age": 10},
         {"name": "Annie", "age": 30},
         {"name": "Ben", "age": 20}]

# sort by age
print(sorted(list1, key=lambda i: i['age']))

# sort by name and age
print(sorted(list1, key=lambda i: (i['age'], i['name'])))

# sort by name
print(sorted(list1, key=lambda i: i['name']))

Output:

Python sort list of dictionaries

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

Answer: Use sorted() method, The sorted() function takes a key= parameter. Example sorted by name.

my_list = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]

res = sorted(my_list, key=lambda k: k['name'])

print(res)

Output: [{‘name’: ‘Bart’, ‘age’: 10}, {‘name’: ‘Homer’, ‘age’: 39}]

Alternatively, you can use operator.itemgetter instead of defining the function yourself

from operator import itemgetter

my_list = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]

res = sorted(my_list, key=itemgetter('name'))
print(res)

Add reverse=True to sort in descending order

res = = sorted(list, key=itemgetter('name'), reverse=True)

Do comment if you have any doubts and suggestions on this Python dictionary tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.