In this notebook, we will learn about how to use Python sort and sorted methods to sort different types of data structures.
Let us start with simple example.
Let us initialize a Python list of numbers.
# initializing a list
digits = [4, 3, 5, 1, 2, 0, 6]
To sort, Python has sort() method. By default Python Sort the numbers in ascending order that is from low to high.
# sorting the digits
digits.sort()
# printing the digits
print(digits)
To sort the number in increasing order, specify the option "reverse"=True as shown below.
# initializing a list
digits = [4, 3, 7, 5, 1, 2, 0, 6]
# sorting the digits in descending order
digits.sort(reverse=True)
# printing the digits
print(digits)
Let us say, we have list of negative and positive numbers in a list and we want to sort the list in ascending order based on the aboslute value.
To do that we can write a Python function which would convert any negative number to absolute number and then pass that function as an argument to sort method.
digit = [1,-6,4,-8,20,10,8,-2,6]
#absvalue is a function that takes a number and returns its absolute value.
def absvalue(dig):
return abs(dig)
digit.sort(key = absvalue)
print(digit)
We can also achieve the above using Python lambda as shown below.
# passed in a lambda expression
digit.sort(key = lambda dig: abs(dig))
print(digit)
sort() method only works on lists, but the sorted() function can work on any iterable object such as lists, tuples, dictionaries, and others.
digit = [6, 9, 3, 1]
#used sorted for list
sorted(digit)
tuple_digits = (9,7,33,3, 1, 4, 5, 2)
#tuple sorted by same order
new_tuple_list = sorted(tuple_digits)
print(new_tuple_list)
Note - By default sorted, sorts the object in an ascending order. However we can specify the order using the optional keyword reverse.
tuple_digits = (9,7,33,3, 1, 4, 5, 2)
#tuple sorted by reverse order
new_tuple_list = sorted(tuple_digits, reverse=True)
print(new_tuple_list)
dictionary_digits = {5, 5, 10, 1, 0}
digit_dictionary_sorted = sorted(dictionary_digits)
print(digit_dictionary_sorted)
We can also sort strings using sorted. Python Sorted treats string as a collection of characters and would sort the characters in alphabetical order.
Strings are defined in single or double quotes in Python. Check out more about strings and literals here.
string_digit_value = '984521'
string_words = 'welocme my friends'
#sorting the string_digit_value
sorted_string_digit = sorted(string_digit_value) #sorts each number
#sorting the string_words
sorted_string = sorted(string_words) #sorts each character
print(sorted_string_digit)
print(sorted_string)
If you note above, the first variable contains digits but is defined as a string since it is enclosed in single quotes. Similarly the second variable 'string_words' is also by default sort by characters by Python sorted method.
Ok but what if we want to sort by words.
Checkout below code to see how strings can be sorted by words. Note to sort by words we need to provide a list of words to Python sorted method. For this we can use split() method. string_words.split() splits the sentence in to list of words. Words are then sort by starting letter of each word.
string_words = 'welcome my friends'
sorted_string_words = sorted(string_words.split())
print(" ".join(sorted_string_words))
Here is another example of string sort.
char = 'njzpqcebad'
#sort by normal order
char_string = ''.join(sorted(char))
print(char_string)
#sort by reverse order
char_string_reverse = ''.join(sorted(char, reverse=True))
print(char_string_reverse)
The below list contains each person and age as one tuple.
Here from each element of the tuples_list, age is passed in to the lambda function as a parameter which is used to sort the entire list. The expected output is a list which is sorted by age in ascending order.
tuples_list = [
('ram', 27 ),
('sham', 25 ),
('akash', 31 )
]
Age_sorting = sorted(tuples_list, key = lambda age: age[1])
print(Age_sorting)
If we don't specify the sort key, list will be sorted alphabetically based on name.
tuples_list = [
('ram', 27 ),
('sham', 25 ),
('akash', 31 )
]
# now strings are sorted alphabetically
age_name_list = sorted(tuples_list)
print(age_name_list)
Below code will sort Python dictionary by key and return only keys.
names_dict = {'John': 17,
'Alex': 42,
'Jamre': 71,
'Renee': 29
}
print(sorted(names_dict))
If you want to get both keys and values, you have to provide an option "key" to sorted method. Remember dictionary doen't retain the order therefore if you try to sort dictionary you always get the list back. In this case it will be list of tuples.
In below snippet, we are using package operator to sort the dictionary by key.
import operator
names_dict = {'John': 17,
'Alex': 42,
'Jamre': 71,
'Renee': 29
}
# sorted by the name
sorted(names_dict.items(), key=operator.itemgetter(0))
Similarly we can sort by value also.
import operator
names_dict = {'John': 17,
'Alex': 42,
'Jamre': 71,
'Renee': 29
}
# sort by the age
sorted(names_dict.items(), key=operator.itemgetter(1))
In python3+, we can use lambda function to sort by key.
names_dict = {'John': 17,
'Alex': 42,
'Jamre': 71,
'Renee': 29
}
#sort by name
sorted(names_dict.items(), key=lambda kv: kv[0])
names_dict = {'John': 17,
'Alex': 42,
'Jamre': 71,
'Renee': 29
}
#sort by age
sorted(names_dict.items(), key=lambda kv: kv[1])
Related Notebooks
- Pandas How To Sort Columns And Rows
- How to Sort Pandas DataFrame with Examples
- Python Iterators And Generators
- Strftime and Strptime In Python
- String And Literal In Python 3
- Learn And Code Confusion Matrix With Python
- Summarising Aggregating and Grouping data in Python Pandas
- Merge and Join DataFrames with Pandas in Python
- Polynomial Interpolation Using Python Pandas Numpy And Sklearn