Sorting a Dictionary in Python. How to sort a dictionary in python | by Luay Matalka | Towards Data Science

We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python’s built-in sorted() function. Just like with other iterables, we can sort dictionaries based on different criteria depending on the key argument of the sorted() function.
In this tutorial, we will learn how to sort dictionaries using the sorted() function in python.
The sorted() function can accept three parameters: the iterable, the key, and reverse.
sorted(iterable, key, reverse)
In contrast to the sort() method which only works on lists, the sorted() function can work on any iterable, such as lists, tuples, dictionaries, and others. However, unlike the sort() method which returns None and modifies the original list, the sorted() function returns a new list while leaving the original object unchanged.
Note: No matter what iterable is passed in to the sorted() function, it always returns a list.
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
Let’s say that we have a dictionary, with the keys being names, and the values being ages.
dictionary_of_names = {'beth': 37,                        'jane': 32,                       'john': 41,                        'mike': 59}
If we just pass in the entire dictionary as the iterable to the sorted() function, we will get the following output:
print(sorted(dictionary_of_names))# ['beth', 'jane', 'john', 'mike']
As we can see, if we pass in the entire dictionary as the iterable to the sorted() function, it returns a list that contains only the keys sorted alphabetically.
towardsdatascience.com
If we want to get a sorted copy of the entire dictionary, we need to use the dictionary items() method:
print(dictionary_of_names.items())# dict_items([('beth', 37), ('jane', 32), ('john', 41), ('mike', 59)])
Notice how the items() method returns a dict_items object, which looks similar to a list of tuples. This dict_items object is an iterable. Thus, it can be passed in as the iterable to the sorted() function.
We can sort this dict_items object the same way we sorted the list of tuples seen earlier. For example, to sort by the second element in each tuple, which would be the age, we can use the following code:
sorted_age = sorted(dictionary_of_names.items(), key = lambda kv: kv[1])print(sorted_age)# [('jane', 32), ('beth', 37), ('john', 41), ('mike', 59)]
Notice how the sorted() function returns a list of tuples, sorted by the age (or second element in each tuple). To convert this list of tuples into a dictionary, we can use the built-in dict() function:
sorted_dictionary = dict(sorted_age)print(sorted_dictionary)# {'jane': 32, 'beth': 37, 'john': 41, 'mike': 59}
Now we have a dictionary sorted by age!
Let’s say that we want to create a function that when passed a list of numbers, returns a sorted dictionary that contains the numbers and their counts in ascending order. Thus, we can have the keys of the dictionary being the different elements (or numbers) in the list, and their corresponding values equal to the number of times that specific element (or number) shows up in the list.
Well, we can accomplish this task with the following function:
nums = [1,1,7,3,5,3,2,9,5,1,3,2,2,2,2,2,9]def count(num_list):    count_dict = {}    for num in num_list:        count_dict[num] = num_list.count(num)    return dict(sorted(count_dict.items(), key=lambda x:x[1]))print(count(nums))# {7: 1, 5: 2, 9: 2, 1: 3, 3: 3, 2: 6}
We first define the function count() with one parameter, num_list. Within the function, we first create an empty dictionary, count_dict. Then as we loop through num_list, which will be the list passed as an argument to the function, using a for loop, we are creating key:value pairs in count_dict. The key will equal the current number we are on while iterating through num_list, and its corresponding value is equal to the count of that number in num_list. Finally, we return the sorted dictionary.
count() is a list method that returns the number of times the value we pass in occurs in our list.
We can further shorten this function by using a dictionary comprehension to create the count_dict dictionary instead of a for loop:
def count(num_list):    count_dict = {num:num_list.count(num) for num in num_list}    return dict(sorted(count_dict.items(), key=lambda x:x[1]))
We use curly brackets to establish that we want to create a dictionary (as opposed to a list where we would use brackets in a list comprehension). Then, as we loop over num_list, we are creating key:value pairs as follows: num:num_list.count(num), where the key is the number (or num), and its value being the count of that number in num_list.
We can shorten this function to only one line of code by using the items() method directly on the dictionary comprehension:
def count(num_list):    return dict(sorted({num:num_list.count(num) for num in num_list}.items(), key=lambda x:x[1]))
For more information on dictionary comprehensions, check out the following:
towardsdatascience.com
In this tutorial, we briefly reviewed the sorted() function. We learned how the sorted() function works on any iterable object (without modifying it) and returns a new list, but the sort() method only works on lists and modifies them in-place and returns None. Lastly, we saw how we can use the sorted() function to sort dictionaries in python.