VOOZH about

URL: https://www.geeksforgeeks.org/python/ways-sort-list-dictionaries-values-python-using-lambda-function/

⇱ Ways to sort list of dictionaries by values in Python - Using lambda function - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 14 Nov, 2025

In Python, sorting a list of dictionaries can be done efficiently using the built-in sorted() function combined with a lambda function. A lambda function is a small anonymous function with any number of arguments and a single expression that is returned.

Syntax:

lambda arguments: expression

Example:

Input: [{"name": "Harry", "marks": 85},
{"name": "Robin", "marks": 92},
{"name": "Kevin", "marks": 78}]

Output: (sorted by marks ascending):
[{'name': 'Kevin', 'marks': 78},
{'name': 'Harry', 'marks': 85},
{'name': 'Robin', 'marks': 92}]

Sort by Single Key

Sort a list of dictionaries using the values of a single key, either in ascending or descending order, to organize data efficiently.


Output
Sorted by age:
[{'name': 'Kevin', 'age': 19}, {'name': 'Harry', 'age': 20}, {'name': 'Robin', 'age': 20}]

Explanation:

  • sorted(dic, key=lambda x: x['age']): sorts the list of dictionaries in ascending order based on the 'age' value of each dictionary.
  • If two items have the same 'age', Python keeps them in the same order as they appeared in the original list.

Sort by Multiple Keys

Sort a list of dictionaries using more than one key, so if the first key is the same, the next key decides the order.

Output

[{'name': 'Kevin', 'age': 19}, {'name': 'Harry', 'age': 20}, {'name': 'Robin', 'age': 20}]

Explanation:(sorted(dic, key=lambda x: (x['age'], x['name'])): Sorts the list of dictionaries first by "age" in ascending order and if ages are equal then by "name" in alphabetic order.

Sort by Key in Descending Order

Sort a list of dictionaries by a key in descending order, from largest to smallest.

Output

[{'name': 'Harry', 'age': 20}, {'name': 'Robin', 'age': 20}, {'name': 'Kevin', 'age': 19}]

Explanation:

  • key=lambda x: x['age']: sorts the dictionaries based on the 'age' value.
  • reverse=True: sorts in descending order.

Related Article:

Comment