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

Previous article of this segment dealt with sorting list of dictionaries by values using lambda function.

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

This article aims at performing this functionality using itemgetter and showing visible differences.

Itemgetter can be used instead of lambda function to achieve the similar functionality. Outputs in same way as sorted() and lambda, but has different internal implementation. It takes 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 working. The code is explained below

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code demonstrate the working of sorted()
# and itemgetter
  
# importing "operator" for implementing itemgetter
from operator import itemgetter
  
# Initializing list of dictionaries
lis = [{ "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(lis, 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(lis, 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(lis, key=itemgetter('age'),reverse = True)

chevron_right


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'}]