In this article, you will learn how to sort the list of dictionaries using values in Python. We will use inbuilt method calls sorted to sort the dictionary.
Steps To Sort Dictionaries
We will follow the steps mentioned below to sort a dictionary using values.
- Pass the list containing dictionaries and keys to the sorted method.
- We can pass the keys in two different ways
- 1.Using lambda function
- 2.Using itemgetter method
- We can pass the keys in two different ways
Let's see the examples.
1. Using a lambda function
Example
## list of dictionaries dicts = [ {"name" : "John", "salary" : 10000}, {"name" : "Emma", "salary" : 30000}, {"name" : "Harry", "salary" : 15000}, {"name" : "Aslan", "salary" : 10000} ] ## sorting the above list using 'lambda' function ## we can reverse the order by passing 'reverse' as 'True' to 'sorted' method print(sorted(dicts, key = lambda item: item['salary']))
If you run the above program, we will get the following results.
[{'name': 'John', 'salary': 10000}, {'name': 'Aslan', 'salary': 10000}, {'name': 'Harry', 'salary': 15000}, {'name': 'Emma', 'salary': 30000}]
2. Using itemgetter Method
The processing of sorting list of dictionaries using the itemgetter is similar to the above process. We pass the value to the key using itemgetter method, that's the only difference. Let's see.
Example
## importing itemgetter from the operator from operator import itemgetter ## list of dictionaries dicts = [ {"name" : "John", "salary" : 10000}, {"name" : "Emma", "salary" : 30000}, {"name" : "Harry", "salary" : 15000}, {"name" : "Aslan", "salary" : 10000} ] ## sorting the above list using 'lambda' function ## we can reverse the order by passing 'reverse' as 'True' to 'sorted' method print(sorted(dicts, key = itemgetter('salary')))
Output
If you run the above program, we will get the following results.
[{'name': 'John', 'salary': 10000}, {'name': 'Aslan', 'salary': 10000}, {'name': 'Harry', 'salary': 15000}, {'name': 'Emma', 'salary': 30000}]