How do i return a sorted dictionary in python?

Introduction

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.

sorted() function

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.

Sorting a Dictionary

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.

Using the items() method

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!

Example- Counting Numbers in a List

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.

Using a Dictionary Comprehension

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:

Conclusion

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.

How do I print a sorted dictionary in Python?

First, sort the keys alphabetically using key_value. iterkeys() function. Second, sort the keys alphabetically using the sorted (key_value) function & print the value corresponding to it. Third, sort the values alphabetically using key_value.

Which method returns a sorted list of the dictionary keys?

items() method is used to return the list with all dictionary keys with values. It returns a view object that displays a list of a given dictionary's (key, value) tuple pair.

How do you reverse a sorted dictionary in Python?

Use dict. items() to get a list of tuple pairs from d and sort it using a lambda function and sorted(). Use dict() to convert the sorted list back to a dictionary. Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.

Does sorted () returns a new list?

The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order. The original list is not changed. It's most common to pass a list into the sorted() function, but in fact it can take as input any sort of iterable collection.