Sorted() function using a key parameter in Python
Different Ways of Using Sorted Function in Python
Sorted(): Sorted function will return new sorted list of the iterable object(list,dictionary,tuple). By default, it will sort in ascending order.
Strings-Sorting is done based on ASCII values.
key(Optional): If we specify key, it will sort the iterable based on the function specified in the key.
reverse(Optional): By default, it will sort the iterable in ascending order. If reverse=True, it will sort the iterable in descending order.
We can also sort the iterable based on the function specified in the key parameter. It can be
- Built-in function
- User-defined function
- Lambda function
1. Built-in function
len()-It will count the length of the object. If we specify
len as a key parameter in the sorted function, it will sort the iterable based on the length.
abs()– It will return the absolute value of a number. If we specify
abs as a key parameter, it will sort based on the absolute value.
str.lower()-str.lower() will convert all uppercase characters to lower case.If we mention key as str.lower, it will perform lower on all items present in the iterable, and then sort it.
2. User-Defined Function
We can specify the key as user-defined functions also. It will sort the iterable based on user-defined function.
Example 1: By default, the sorted function will sort a list of tuples based on the first element. Here we mentioned a user-defined function to take the second element. So, now sorted function sort the list of tuples based on the second element
Example 2: We can sort a list of class objects by specifying user-defined functions.
In the below example,
- Class Student has three attributes name,rollno, grade.
- Created 3 Student objects s1,s2,s3
- Created list s4 containing all three Student objects(s1,s2,s3)
- Now have to sort the list of Student objects
- Defined function(sort_key) to return the attribute rollno.
- In sorted function, mentioned key as user-defined function(sort_key)
- Now sorted(), returns a list of Student objects sorted by rollno.
Note: If we didn’t specify key for sorting class objects, it will raise TypeError. Since, it doesn't know on what basis to sort the class objects.
We can mention the key as lambda function also. Based on that lambda function, sorted() will sort the iterable.
Example 1: Sorting list of class objects based on the lambda function mentioned in the key parameter.
Example 2: Sorting list of tuples based on the second element in the tuple. Lambda function which returns the second element is mentioned as key.
operator is a built-in module that contains many operators. itemgetter(n) constructs a function that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.
Example:1 Sorting list of tuples based on the third element in the tuple. itemgetter() will return the function that fetches the third element in the tuple.
By default, if we didn’t specify the key, it will sort based on the first element in the tuple.
from operator import itemgetter l1=[(1,2,3),(3,1,1),(8,5,3),(3,4,2)] #Sorted based on third element in the tuple. print (sorted(l1,key=itemgetter(2))) #Output:[(3, 1, 1), (3, 4, 2), (1, 2, 3), (8, 5, 3)]
Example:2 Sorting list of dictionaries based on the key(age) in the dictionary.
Example:3 Sorting dictionary values using itemgetter.
operator. attrgetter (*attrs)
Return a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes. The attribute names can also contain dots.
Example: Sorting list of class objects by using attrgetter. attrgetter function can get the attribute of the object and the sorted function will sort based on that attribute.
Multiple level sorting
- We can do multiple level sorting by itemgetter also.
In the below example, it will sort the dictionary values based on the second element. In case if the second element is equal, then it will sort based on the third element.
- multiple levels sorting by using the lambda function in the key parameters.
In the below example, it will sort the list of tuples based on the second element, if the second element is equal means it will sort based on the third element.
Mixed data types
sorted function doesn’t support mixed data types. It will raise TypeError.
1. When sorting a list of class objects, the key is a must. If we didn’t mention the key, it will raise TypeError.
2. For sorting a list of class objects, we can use user-defined function/lambda function/attrgetter as a key parameter.
3. sorted() function-Return type is List
4. sort method will sort the original list itself. the sorted function will return a new list. It won’t modify the original list.
sort method is used to sort only list. sort method is not available for string, tuple, dictionary.