
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Ways to sort list of dictionaries by values in Python Using lambda function
When it is required to sort the list of dictionaries based on values, the lambda function can be used.
Below is the demonstration of the same −
Example
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=lambda i: i['age'])) print("The list sorted by age and name is : ") print(sorted(my_list, key=lambda i: (i['age'], i['name']))) print("The list sorted by age in descending order is : ") print(sorted(my_list, key=lambda i: i['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 list of dictionary elements is defined and is displayed on the console.
The sorted method is used, and the key is specified as ‘lambda’.
The list of dictionary is again sorted using lambda as two parameters.
The output is displayed on the console.
- Related Articles
- Ways to sort list of dictionaries by values in Python Using itemgetter
- Ways to sort list of dictionaries by values in Python
- Ways to sort list of dictionaries using values in python
- Sort list of dictionaries by values in C#
- How to sort a list of dictionaries by values of dictionaries in C#?
- Python program to Sort a List of Dictionaries by the Sum of their Values
- How do I sort a list of dictionaries by values of the dictionary in Python?
- Python – Sort Dictionaries by Size
- Python - Filter dictionaries by values in Kth Key in list
- Sort Python Dictionaries by Key or Value
- Python | Sort the values of first list using second list
- How can I sort one list by values from another list in Python?
- Flatten given list of dictionaries in Python
- Sort Dictionary key and values List in Python
- How to sort a dictionary in Python by values?

Advertisements