Member-only story
Sorting a Dictionary in Python
How to sort a 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.