Ways to sort list of dictionaries by values in Python

PythonProgrammingServer Side Programming

Here one dictionary is given, our task is to sort by their values. Two values are present in this dictionary one is name and another is roll. First we display sorted list by their roll using lambda function and in-built sorted function.

Second we display sorted list by the name and roll and third by their name.

Example code

Live Demo

# 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

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}]
raja
Published on 20-Nov-2018 07:44:50
Advertisements