Ways to sort list of dictionaries by values in Python - Using lambda function
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.
dic = [
{"name": "Harry", "age": 20},
{"name": "Robin", "age": 20},
{"name": "Kevin", "age": 19}
]
print("Sorted by age:")
print(sorted(dic, key=lambda x: x['age']))
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.
print("\nSorted by age and name:")
print(sorted(dic, key=lambda x: (x['age'], x['name'])))
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.
print("\nSorted by age (descending):")
print(sorted(dic, key=lambda x: x['age'], reverse=True))
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.