Python Sort And Sorted

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.

In [1]:
# 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.

In [2]:
# sorting the digits
digits.sort()
# printing the digits
print(digits)
[0, 1, 2, 3, 4, 5, 6]

To sort the number in increasing order, specify the option "reverse"=True as shown below.

In [3]:
# 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)
[7, 6, 5, 4, 3, 2, 1, 0]

Sort the Python list based on absolute value

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.

In [4]:
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) 
[1, -2, 4, -6, 6, -8, 8, 10, 20]

We can also achieve the above using Python lambda as shown below.

In [5]:
# passed in a lambda expression
digit.sort(key = lambda dig: abs(dig))
print(digit)
[1, -2, 4, -6, 6, -8, 8, 10, 20]

sort() method only works on lists, but the sorted() function can work on any iterable object such as lists, tuples, dictionaries, and others.

Sort List using Python sorted

In [6]:
digit = [6, 9, 3, 1]
#used sorted for list
sorted(digit)
Out[6]:
[1, 3, 6, 9]

Sort Tuple using Python sorted

In [7]:
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)
[1, 2, 3, 4, 5, 7, 9, 33]

Note - By default sorted, sorts the object in an ascending order. However we can specify the order using the optional keyword reverse.

In [8]:
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)
[33, 9, 7, 5, 4, 3, 2, 1]

Sort Python Dictionary using sorted

In [9]:
dictionary_digits = {5, 5, 10, 1, 0}
digit_dictionary_sorted = sorted(dictionary_digits)
print(digit_dictionary_sorted)
[0, 1, 5, 10]

Sort Python Strings using 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.

In [10]:
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)
['1', '2', '4', '5', '8', '9']
[' ', ' ', 'c', 'd', 'e', 'e', 'e', 'f', 'i', 'l', 'm', 'm', 'n', 'o', 'r', 's', 'w', 'y']

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.

Sort Python Strings 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.

In [11]:
string_words = 'welcome my friends'
sorted_string_words = sorted(string_words.split())
print(" ".join(sorted_string_words))
friends my welcome

Here is another example of string sort.

In [12]:
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)
abcdejnpqz
zqpnjedcba

Sort Python list of Tuples with key value pairs

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.

In [13]:
tuples_list = [
    ('ram', 27 ),
    ('sham', 25 ),
    ('akash', 31 )
]
Age_sorting = sorted(tuples_list, key = lambda age: age[1])
print(Age_sorting) 
[('sham', 25), ('ram', 27), ('akash', 31)]

If we don't specify the sort key, list will be sorted alphabetically based on name.

In [14]:
tuples_list = [
    ('ram', 27 ),
    ('sham', 25 ),
    ('akash', 31 )
]
# now strings are sorted alphabetically
age_name_list = sorted(tuples_list)

print(age_name_list) 
[('akash', 31), ('ram', 27), ('sham', 25)]

Python sort dictionary by key

Below code will sort Python dictionary by key and return only keys.

In [15]:
names_dict = {'John': 17, 
                       'Alex': 42,
                       'Jamre': 71, 
                       'Renee': 29
}
print(sorted(names_dict))
['Alex', 'Jamre', 'John', 'Renee']

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.

In [16]:
import operator
names_dict = {'John': 17, 
              'Alex': 42,
              'Jamre': 71, 
              'Renee': 29
}
# sorted by the name
sorted(names_dict.items(), key=operator.itemgetter(0))
Out[16]:
[('Alex', 42), ('Jamre', 71), ('John', 17), ('Renee', 29)]

Python sort dictionary by value

Similarly we can sort by value also.

In [17]:
import operator
names_dict = {'John': 17, 
              'Alex': 42,
              'Jamre': 71, 
              'Renee': 29
}
# sort by the age
sorted(names_dict.items(), key=operator.itemgetter(1))
Out[17]:
[('John', 17), ('Renee', 29), ('Alex', 42), ('Jamre', 71)]

Sort Dictionary by key in Python3+

In python3+, we can use lambda function to sort by key.

In [18]:
names_dict = {'John': 17, 
               'Alex': 42,
               'Jamre': 71, 
               'Renee': 29
}
#sort by name
sorted(names_dict.items(), key=lambda kv: kv[0])
Out[18]:
[('Alex', 42), ('Jamre', 71), ('John', 17), ('Renee', 29)]

Sort Dictionary by value in Python3+

In [19]:
names_dict = {'John': 17, 
               'Alex': 42,
               'Jamre': 71, 
               'Renee': 29
}
#sort by age
sorted(names_dict.items(), key=lambda kv: kv[1])
Out[19]:
[('John', 17), ('Renee', 29), ('Alex', 42), ('Jamre', 71)]