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
from operator import itemgetter
list = [{ "name" : "Nandini" , "age" : 20 },
{ "name" : "Manjeet" , "age" : 20 },
{ "name" : "Nikhil" , "age" : 19 }]
print "The list printed sorting by age: "
print sorted ( list , key = itemgetter( 'age' ))
print ( "\r" )
print "The list printed sorting by age and name: "
print sorted ( list , key = itemgetter( 'age' , 'name' ))
print ( "\r" )
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
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
22 Feb, 2023
Like Article
Save Article