How to Sort with lambda in Python

In this post, we are going to learn how to Sort with lambda in Python. Python’s two methods sort() and sorted() help us to sort any data structure in ascending by default. The Python sort() and sorted() method takes an optional key parameter that use to pass a custom sorting order function to perform sorting. We will pass the lambda function as a key parameter to the sort() function or sorted() method.

Python sorted() method


The Python inbuilt sorted() method is used to sort the data structure(list, tuple, dictionary string) and returns a new sorted data structure object.

Syntax for sorted() Method

sorted(iterable,key_function,reverse)
  • iterable: required parameter, represents the object that we want to sort.
  • Key_function: It is an optional parameter, It allows to pass a function to custom sorting.
  • Reverse: This is an optional parameter, We use this parameter when sorting the dictionary in descending order.

1. Sort list of tuples using sort() lambda


In this Python program example, we are sorting a list of tuples by passing a lambda to sort() method. Where the list is passed as the first argument to sort method lambda is passed as a key parameter value and the sorting position is set as the second element of the list.

mylist = [("apple", 25), ("banana", 20), ("orange", 5)]
mylist.sort(key=lambda item:item[1])
print(mylist)

Output

[('orange', 5), ('banana', 20), ('apple', 25)]

2. Sort list of numeric using sorted() method


In this Python program example, every list element is prefixed with ’empid’ in the key parameter of the lambda function, we have specified to ignore the first 5 characters in the sorted method.

mylist = ['empId02', 'empId04', 'empId06', 'empId08', 'empId01', 'empId13']

sortedlst = sorted(mylist, key=lambda item: int(item[5:]))

print('sorted list:\n',sortedlst)

Output

sorted list:
 ['empId01', 'empId02', 'empId04', 'empId06', 'empId08', 'empId13']

3. Sorting list of list Using sorted function


In this Python example code, we are sorting the nested lists by passing the lambda function to the key parameter of the sorted() method.

list_of_lists = [['Jack', '30', '100'], ['Mack', '30'], ['Kon', '30', '100', 'US']]


sorted_list = []

for item in range(len(list_of_lists)):
   
   for j in range(len(list_of_lists[item])):
     
      result_list = sorted(list_of_lists [item], key=lambda x: x[0])
   
   sorted_list.append(result_list)

print("sorted list:\n {}".format(sorted_list))

Output

sorted list:
 [['100', '30', 'Jack'], ['30', 'Mack'], ['100', '30', 'Kon', 'US']]

4. sort list of dictionaries by lambda


In this Python code example, we will understand how to sort the list of dictionaries by multiple keys using the sorted() method by passing a lambda to the key parameter of the sorted method.

  • sorting dictionary by key (name).
  • sorting dictionary by multiple keys( name,marks)
  • sort list of dictionary in reverse order using ‘name’ key


list_of_dict = [{"name": "Jack", "age": 20, "marks":100},
            {"name": "Jack", "age": 35, "marks":100},
            {"name": "Jack", "age": 30, "marks":100}]


print("sort list_of_dict by name:\n", sorted(list_of_dict, key=lambda item: item['name']))


print("\nSort list_of_dict by  name  and marks :\n", sorted(list_of_dict, key=lambda item: (item['name'], item['marks'])))


print("\nsort list_of_dict descending order by name:\n", sorted(list_of_dict, key=lambda item: item['name'], reverse=True))

Output

sort list_of_dict by name:
 [{'name': 'Jack', 'age': 20, 'marks': 100}, {'name': 'Jack', 'age': 35, 'marks': 100}, {'name': 'Jack', 'age': 30, 'marks': 100}]

Sort list_of_dict by  name  and marks :
 [{'name': 'Jack', 'age': 20, 'marks': 100}, {'name': 'Jack', 'age': 35, 'marks': 100}, {'name': 'Jack', 'age': 30, 'marks': 100}]

sort list_of_dict descending order by name:
 [{'name': 'Jack', 'age': 20, 'marks': 100}, {'name': 'Jack', 'age': 35, 'marks': 100}, {'name': 'Jack', 'age': 30, 'marks': 100}]

5. Sort dictionary by using lambda


In this Python code example, we are sorting dictionaries by passing the lambda function to the sorted() method.

mydict= {
    "Sachin": 106,
    "Dravid" : 70 ,
    "Sourav" : 80,
    "Dhoni" : 90
    }

sortedDict = sorted(mydict.items(), key=lambda item: item[1])
 
#sorting a dictionary using lambda function
 
print('Sorted Dictionary:\n',sortedDict)
 

Output

Sorted Dictionary:
 [('Dravid', 70), ('Sourav', 80), ('Dhoni', 90), ('Sachin', 106)]

Summary

In this post we have learned how to Sort with lambda in Python using the sort() and sorted() methods.