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

PythonServer Side ProgrammingProgramming

When it is required to sort the list of dictionary based on values, the itemgetter attribute can be used.

Below is the demonstration of the same −

Example

 Live Demo

from operator import itemgetter

my_list = [{ "name" : "Will", "age" : 56},
          { "name" : "Rob", "age" : 20 },
          { "name" : "Mark" , "age" : 34 },
          { "name" : "John" , "age" : 24 }]

print("The list sorted by age is : ")
print(sorted(my_list, key=itemgetter('age')))

print("The list sorted by age and name is : ")
print(sorted(my_list, key=itemgetter('age', 'name')))

print("The list sorted by age in descending order is : ")
print(sorted(my_list, key=itemgetter('age'),reverse = True))

Output

The list sorted by age is :
[{'name': 'Rob', 'age': 20}, {'name': 'John', 'age': 24}, {'name': 'Mark', 'age': 34}, {'name': 'Will',
'age': 56}]
The list sorted by age and name is :
[{'name': 'Rob', 'age': 20}, {'name': 'John', 'age': 24}, {'name': 'Mark', 'age': 34}, {'name': 'Will',
'age': 56}]
The list sorted by age in descending order is :
[{'name': 'Will', 'age': 56}, {'name': 'Mark', 'age': 34}, {'name': 'John', 'age': 24}, {'name': 'Rob',
'age': 20}]

Explanation

  • The required packages are imported.

  • The list of dictionary elements is defined and is displayed on the console.

  • The sorted method is used, and the key is specified as ‘itemgetter’.

  • The list of dictionary is again sorted using itemgetter as two parameters.

  • The output is displayed on the console.

raja
Published on 17-Apr-2021 12:11:17
Advertisements