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


In this article, we will show how to sort a list of dictionaries by the values of the dictionary in Python.

Sorting has always been a useful technique in everyday programming. Python's dictionary is often used in a wide range of applications, from competitive to developer-oriented (example-handling JSON data). It can be useful in certain situations to be able to filter dictionaries based on their values.

Below are the 2 methods to accomplish this task −

  • Using sorted() and itemgetter

  • Using sorted() and lambda functions

What is a Dictionary?

Dictionaries are Python's version of an associative array data structure. A dictionary is a collection of key-value pairs. Each key pair is represented by a key pair and its associated value.

A dictionary is defined by a list of key-value pairs enclosed in curly braces and separated by commas. Each key's value is separated by a colon(:).

A dictionary is an ordered collection of data values that can be accessed using a key. The dictionary is a key-value mapping. The dict() is a constructor used to create instances of the class dict. The element order in a dictionary is undefined. It is possible to iterate over keys, values, or key-value pairs.

Using sorted() and Itemgetter

sorted() Function

The sorted() function returns a sorted list of the iterable object given.

You can choose between ascending and descending order. Numbers are sorted numerically, while strings are arranged alphabetically.

Syntax

sorted(iterable, key=key, reverse=reverse)

Parameters

iterable- It is a sequence.

key − A function that will be executed to determine the order. The default value is None.

reverse − A Boolean expression. True sorts ascending, False sorts descending. The default value is False.

Itemgetter in Python

To achieve similar functionality, the Itemgetter function can be used instead of the lambda function. The same as sorted() and lambda, but with a different internal implementation. It accepts dictionary keys and turns/converts them to tuples. It minimizes overhead while also being speedier and more efficient.

To work with the itemgetter the "operator" module must be imported.

  • Performance − In terms of performance, itemgetter beats lambda functions in the context of time.

  • Concise − When accessing numerous values, itemgetter appears more simple than lambda functions.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the import keyword to import the itemgetter from the operator module for implementing the itemgetter.

  • Create a variable to store the input list of dictionaries.

  • Print the sorted list by score using the sorted() function(returns a sorted list of the iterable object given.)and itemgetter

Example

The following program returns the sorted input list of dictionaries by the values using sorted() and itemgetter −

# importing itemgetter from the operator module
# (for implementing itemgetter)
from operator import itemgetter
 
# Input list of dictionaries
inputList = [{"cricketer": "Dhoni", "score": 75},{"cricketer": "Virat Kohli", "score": 90},
   {"cricketer": "Hardik Pandya", "score": 65}]
 
print("The sorted list by score: ")
# printing the sorted list by score using the sorted() and itemgetter
print(sorted(inputList, key=itemgetter('score')))
 
print("\r")
 
# printing the sorted list by both cricketer, score using the sorted() and itemgetter
# Here Dhoni comes first since 'D' comes first then H, and V alphabetically 
print("The sorted list by both cricketer and score: ")
print(sorted(inputList, key=itemgetter('cricketer', 'score')))
 
print("\r")
 
# printing the sorted list by the score in descending order 
# using the sorted() and itemgetter
print("The sorted list by the score in descending order: ")
print(sorted(inputList, key=itemgetter('score'), reverse=True))

Output

On executing, the above program will generate the following output −

The sorted list by score: 
[{'cricketer': 'Hardik Pandya', 'score': 65}, {'cricketer': 'Dhoni', 'score': 75}, {'cricketer': 'Virat Kohli', 'score': 90}]

The sorted list by both cricketer and score: 
[{'cricketer': 'Dhoni', 'score': 75}, {'cricketer': 'Hardik Pandya', 'score': 65}, {'cricketer': 'Virat Kohli', 'score': 90}]

The sorted list by the score in descending order: 
[{'cricketer': 'Virat Kohli', 'score': 90}, {'cricketer': 'Dhoni', 'score': 75}, {'cricketer': 'Hardik Pandya', 'score': 65}]

Using sorted() and lambda Functions

Example

The following program returns the sorted input list of dictionaries by the values using sorted() and lambda() functions −

# Input list of dictionaries
inputList = [{"cricketer": "Dhoni", "score": 75},{"cricketer": "Virat Kohli", "score": 90},
   {"cricketer": "Hardik Pandya", "score": 65}]
 
print("The sorted list by score: ")
# printing the sorted list by score using the sorted() and lambda functions
print(sorted(inputList, key=lambda k: k['score']))
 
print("\r")
 
# printing the sorted list by both cricketer, and score using the sorted() and lambda functions
# Here Dhoni comes first since 'D' comes first then H, and V alphabetically 
print("The sorted list by both cricketer and score: ")
print(sorted(inputList, key=lambda k: (k['cricketer'], k['score'])))
 
print("\r")
 
# printing the sorted list by the score in descending order 
# using the sorted() and lambda functions
print("The sorted list by the score in descending order: ")
print(sorted(inputList, key=lambda k: k['score'], reverse=True))

Output

On executing, the above program will generate the following output −

The sorted list by score: 
[{'cricketer': 'Hardik Pandya', 'score': 65}, {'cricketer': 'Dhoni', 'score': 75}, {'cricketer': 'Virat Kohli', 'score': 90}]

The sorted list by both cricketer and score: 
[{'cricketer': 'Dhoni', 'score': 75}, {'cricketer': 'Hardik Pandya', 'score': 65}, {'cricketer': 'Virat Kohli', 'score': 90}]

The sorted list by the score in descending order: 
[{'cricketer': 'Virat Kohli', 'score': 90}, {'cricketer': 'Dhoni', 'score': 75}, {'cricketer': 'Hardik Pandya', 'score': 65}]

Conclusion

We learned how to sort a list of dictionaries by values using two different ways in this post. In this article, we also learned about lambda functions and item getter.

Updated on: 31-Jan-2023

389 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements