English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to Sort a List of Dictionaries by Value in Python

Here is a dictionary, our task is to sort them by their values. There are two values in this dictionary, one is name, and the other is roll. First, we use the lambda function and the built-in sorting function to display the sorted list by roll.

Secondly, we display the sorted list by name and roll, third, by name.

Example code

# Initializing list of dictionaries 
my_list1 = [{ "name" : "Adwaita", "roll" : 100},
{ "name" : "Aadrika", "roll" : 234 },
{ "name" : "Sakya" , "roll" : 23 }
print ("The list is sorted by roll: ")
print (sorted(my_list1, key = lambda i: i['roll']) )
print ("\r")
print ("The list is sorted by name and roll: ")
print (sorted(my_list1, key = lambda i: (i['roll'], i['name'])) )
print ("\r")
print ("The list is sorted by roll in descending order: ")
print (sorted(my_list1, key = lambda i: i['roll'],reverse=True) )

Output result

The list is sorted by roll: 
[{'name': 'Sakya', 'roll': 23}, {'name': 'Adwaita', 'roll': 100}, {'name': 'Aadrika', 'roll': 234}
The list is sorted by name and roll: 
[{'name': 'Sakya', 'roll': 23}, {'name': 'Adwaita', 'roll': 100}, {'name': 'Aadrika', 'roll': 234}
The list is sorted by roll in descending order: 
[{'name': 'Aadrika', 'roll': 234}, {'name': 'Adwaita', 'roll': 100}, {'name': 'Sakya', 'roll': 23}