Python program to sort a list of dictionaries using Lambda expression

Published by user on

In this post, we will see how to sort the list of dictionaries using lambda in python. lambda is a keyword in python which is used to define an anonymous function.

Algorithm
Step 1: Declare a list of employees.
Step 2: Use the sorted() function and lambda expression to sort the list of employees, pass department as a parameter to sort the list based on department.
Step 3: Print the sorted list
Step 4: End

Example

Input 
[{'id': '101', 'name': 'Adam', 'department': 'IT'}, {'id': '102', 'name': 'Ricky', 'department': 'Electronics'}, {'id': '103', 'name': 'Shane', 'department': 'Auto'}]
Output
[{'id': '103', 'name': 'Shane', 'department': 'Auto'}, {'id': '102', 'name': 'Ricky', 'department': 'Electronics'}, {'id': '101', 'name': 'Adam', 'department': 'IT'}]

Program

employees = [{'id':'101', 'name':'Adam', 'department':'IT'}, {'id':'102', 'name':'Ricky', 'department':'Electronics'}, {'id':'103', 'name': 'Shane', 'department':'Auto'}]
print("List of employees :")
print(employees)
sorted_employees = sorted(employees, key = lambda x: x['department'])
print("\nSorted List of employees :")
print(sorted_employees)

Output

List of employees :
[{'id': '101', 'name': 'Adam', 'department': 'IT'}, {'id': '102', 'name': 'Ricky', 'department': 'Electronics'}, {'id': '103', 'name': 'Shane', 'department': 'Auto'}]

Sorted List of employees :
[{'id': '103', 'name': 'Shane', 'department': 'Auto'}, {'id': '102', 'name': 'Ricky', 'department': 'Electronics'}, {'id': '101', 'name': 'Adam', 'department': 'IT'}]
Categories: python