Ways to sort list of dictionaries using values in python



In this article, we will see how to sort a list of dictionaries using values. Dictionary represents the key-value pair in Python, enclosed in curly braces. The keys are unique and a colon separates it from value, whereas comma separates the items. With that, the left size before the colon are keys, whereas right its corresponding values.

Let’s say we have the following list of Dictionaries −

[{'name': 'Sam', 'marks': 98}, {'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}]

The output should be the following −

Sorted =
[{'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}, {'name': 'Sam', 'marks': 98}]

Sort List of Dictionaries using values with lamda function in the sorted() method

Example

# list of dictionaries d = [ {"name" : "Sam", "marks" : 98}, {"name" : "Tom", "marks" : 93}, {"name" : "Jacob", "marks" : 97} ] # Display the Dictionary print("Dictionary = \n",d) # Sorting using values with the lambda function print("Sorted = \n",sorted(d, key = lambda item: item['marks']))

Output

Dictionary = 
 [{'name': 'Sam', 'marks': 98}, {'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}]
Sorted = 
 [{'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}, {'name': 'Sam', 'marks': 98}]

Sort List of Dictionaries using values with lamda function in the sorted() method in Descending order

Example

# List of dictionaries d = [ {"name" : "Sam", "marks" : 98}, {"name" : "Tom", "marks" : 93}, {"name" : "Jacob", "marks" : 97} ] # Display the Dictionary print("Dictionary = \n",d) # Sorting using values with the lambda function # The reverse parameter is True for Descending Order sort print("Sorted = \n",sorted(d, key = lambda item: item['marks'], reverse = True))

Output

Dictionary = 
 [{'name': 'Sam', 'marks': 98}, {'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}]
Sorted = 
 [{'name': 'Sam', 'marks': 98}, {'name': 'Jacob', 'marks': 97}, {'name': 'Tom', 'marks': 93}]

Sort List of Dictionaries using values with itemgetter method in the sorted() method

Example

from operator import itemgetter # list of dictionaries d = [ {"name" : "Sam", "marks" : 98}, {"name" : "Tom", "marks" : 93}, {"name" : "Jacob", "marks" : 97} ] # Display the Dictionary print("Dictionary = \n",d) # Sorting using values with the itemgetter function print("Sorted = \n",sorted(d, key = itemgetter('marks')))

Output

Dictionary = 
 [{'name': 'Sam', 'marks': 98}, {'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}]
Sorted = 
 [{'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}, {'name': 'Sam', 'marks': 98}]

Advertisements