Open In App

Ways to sort list of dictionaries by values in Python – Using itemgetter

Last Updated : 22 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will cover how to sort a dictionary by value in Python. To sort a list of dictionaries by the value of the specific key in Python we will use the following method in this article.

In everyday programming, sorting has always been a helpful tool. Python’s dictionary is frequently utilized in a variety of applications, from those involving competition to those involving developers (e.g. handling JSON data). In these circumstances, being able to filter dictionaries according to their values can be helpful.
There are two methods for doing this sorting:

 

What is Itemgetter in Python?

The Itemgetter can be used instead of the lambda function to achieve similar functionality. Outputs in the same way as sorted() and lambda, but has different internal implementation. It takes the keys of dictionaries and converts them into tuples. It reduces overhead and is faster and more efficient. The “operator” module has to be imported for its work. The code is explained below 

  • Performance: itemgetter performs better than lambda functions in the context of time.
  • Concise: : itemgetter looks more concise when accessing multiple values than lambda functions.

Example:

Python3




# Python code demonstrate the working of sorted()
# and itemgetter
 
# importing "operator" for implementing itemgetter
from operator import itemgetter
 
# Initializing list of dictionaries
list = [{"name": "Nandini", "age": 20},
       {"name": "Manjeet", "age": 20},
       {"name": "Nikhil", "age": 19}]
 
# using sorted and itemgetter to print list sorted by age
print "The list printed sorting by age: "
print sorted(list, key=itemgetter('age'))
 
print("\r")
 
# using sorted and itemgetter to print
# list sorted by both age and name
# notice that "Manjeet" now comes before "Nandini"
print "The list printed sorting by age and name: "
print sorted(list, key=itemgetter('age', 'name'))
 
print("\r")
 
# using sorted and itemgetter to print list
# sorted by age in descending order
print "The list printed sorting by age in descending order: "
print sorted(list, key=itemgetter('age'), reverse=True)


Output:

The list printed sorting by age: 
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}]

The list printed sorting by age and name: 
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Manjeet'}, {'age': 20, 'name': 'Nandini'}]

The list printed sorting by age in descending order: 
[{'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}, {'age': 19, 'name': 'Nikhil'}]

Time complexity: O(n log n)
Auxiliary space: O(n)

Next Article -> Ways to sort list of dictionaries by values in Python – Using lambda function



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads