Ways to sort list of dictionaries using values in pythonPythonServer Side ProgrammingProgramming 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. Show Steps To Sort DictionariesWe will follow the steps mentioned below to sort a dictionary using values.
Let's see the examples. 1. Using a lambda functionExampleLive Demo ## 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 MethodThe 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. ExampleLive Demo ## 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')))OutputIf 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}]Hafeezul Kareem Published on 04-Jul-2019 12:08:58 Previous Page Print Page Next Page Advertisements |