![]() |
VOOZH | about |
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.
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 a list of dictionaries using the values of a single key, either in ascending or descending order, to organize data efficiently.
Sorted by age:
[{'name': 'Kevin', 'age': 19}, {'name': 'Harry', 'age': 20}, {'name': 'Robin', 'age': 20}]
Explanation:
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 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: