Back to articles list Articles
9 minutes read

How to Sort a Dictionary in Python

Do you want to learn how to sort a dictionary in Python? In this article, I explain different ways of sorting dictionaries as well as things to keep in mind while doing this operation.

Data structures are fundamental building blocks of any programming language. To create robust and performant software products, one must know how to efficiently use data structures.

Along with lists, tuples, and sets, dictionaries are one of Python’s most used built-in data structures. A dictionary can be defined as an unordered collection of key-value pairs. The keys, as the name suggests, are used for accessing the values. The keys must be unique and immutable, so we can use strings, numbers (int or float), or tuples as keys. On the other hand, values can be of any type. Here are some examples of key-value pairs:

KEY: VALUE
‘color’: ‘blue’
‘version’: 3.23
‘operating-system’: ‘ChromeOS’

Items (i.e. key-value pairs) in a dictionary are not sorted by default, nor do they have an index. But we can sort a dictionary in Python, either sorting by key or by value. In this article, we’ll learn how to sort a dictionary in Python in great detail. If you’re new to Python and don’t know much about data structures, I suggest taking our course Python Data Structures in Practice, which contains over 100 interactive exercises to help you get a comprehensive understanding of Python’s data structures.

How to Create a Dictionary

There are different ways of creating a dictionary in Python. One way is to write zero or more key-value pairs between curly braces. Here are some examples:

>>> # creating an empty dictionary
>>> empty_dict = {}
>>> print(type(empty_dict))


>>> # creating grades dictionary
>>> grades = {'Dennis':'A', 'Betty':'B', 'Antoine':'C', 'Ally':'A'}
>>> print(grades)
{'Dennis': 'A', 'Betty': 'B', 'Antoine': 'C', 'Ally': 'A'}

The grades dictionary consists of four key-value pairs, with names being the keys and the letter grades being the values.

We can also use the dict() constructor to create a dictionary. The key-value pairs can be passed as a list of tuples, where each tuple represents a key-value pair:

>>> # creating grades dictionary with dict constructor
>>> grades = dict([("Dennis","A"), ("Betty","B"), ("Antoine","C"), ("Ally","A")])
>>> print(grades)
{'Dennis': 'A', 'Betty': 'B', 'Antoine': 'C', 'Ally': 'A'}

If the keys are simple strings, we can specify key-value pairs using keyword arguments in the dict() constructor, which is simpler than using a list of tuples:

>>> # creating grades dictionary using keyword arguments
>>> grades = dict(Dennis="A", Betty="B", Antoine="C", Ally="A")
>>> print(grades)
{'Dennis': 'A', 'Betty': 'B', 'Antoine': 'C', 'Ally': 'A'}

And that’s that – we’ve learned some different ways of creating a dictionary. If you’d like to learn more, here is a great article that shows 5 Ways to Create a Dictionary in Python.

We’re getting closer to the main topic of this article, which is how to sort a dictionary. Let’s first cover Python’s built-in sorted() function.

The sorted() Function

We’ll go through a few examples to help you get a comprehensive understanding of how to sort a dictionary in Python. But first, let’s understand the sorted() function, which takes an iterable as an argument and returns a sorted version of that iterable.

The sorted() function is one of Python's built-in functions. To write efficient code and create optimized applications, it’s crucial to know and use built-in functions and algorithms. Our Built-in Algorithms in Python course will help you learn how to use built-in functions, searching and sorting algorithms, and more in 67 interactive exercises.

Here is an example of sorting a list of strings:

>>> names = ["Max", "Jonathan", "David", "Ashely"]
>>> print(sorted(names)
['Ashely', 'David', 'Jonathan', 'Max']

It is important to mention that the sorted() function doesn’t work in place, which means it doesn’t modify the original variable (i.e. in the example above, the names list). Instead, it returns a modified version of the original variable. To use the sorted list of names, we need to assign it to a new variable or to the variable itself.

>>> names = ["Max", "Jonathan", "David", "Ashely"]
>>> names = sorted(names)
>>> print(names)
['Ashely', 'David', 'Jonathan', 'Max']

The sorted() function also takes two optional arguments, which are key (which we will explain below) and reverse. The reverse argument is self-explanatory; when set to ‘True’, the sorting operation is done in reverse order.

>>> names = ["Max", "Jonathan", "David", "Ashely"]
>>> names = sorted(names, reverse=True)
>>> print(names)
['Max', 'Jonathan', 'David', 'Ashely']

When sorting a list of strings, sorting in alphabetical order is the natural thing to do. Similarly, when sorting a numeric iterable, it’s done in increasing or decreasing order depending on the value of the reverse parameter.

The sorted() function can also be used for performing more complex sorting operations with the key parameter. Consider a case where we have a list of tuples and want to sort them:

>>> employees = [("Max", 27), ("Jonathan", 35), ("David", 32), 
>>> ("Ashley", 28)]
>>> print(sorted(employees)
[('Ashley', 28), ('David', 32), ('Jonathan', 35), ('Max', 27)]

Tuples by default are sorted by the first elements (i.e. the keys), which are employee names in this case. What if we want to sort the key-value pairs based on the values, which are the second elements in these tuples? In this case, we can use the key parameter:

>>> employees = [("Max", 27), ("Jonathan", 35), ("David", 32), 
>>> ("Ashley", 28)]
>>> print(sorted(employees, key=lambda employee: employee[1])
[('Max', 27), ('Ashley', 28), ('David', 32), ('Jonathan', 35)]

The lambda function used as the key argument takes the second item (i.e. the item with index 1) from each tuple. We can also use the key and reverse arguments together.

>>> employees = [("Max", 27), ("Jonathan", 35), ("David", 32), 
>>> ("Ashley", 28)]
>>> print(sorted(employees, key=lambda employee: employee[1], reverse=True)
[('Jonathan', 35), ('David', 32), ('Ashley', 28), ('Max', 27)]

How to Sort a Dictionary in Python

Dictionary Keys, Values, and Items

Before we get to sorting a dictionary in Python, let’s first learn how to extract pieces of information from a dictionary.

As mentioned previously, a dictionary consists of key-value pairs. We can extract the keys and values separately from a dictionary using the keys() and values() methods, respectively.

>>> employees = {"Max": 27, "Jonathan": 35, "David": 32, "Ashley": 28}
>>> print(employees.keys())
dict_keys(['Max', 'Jonathan', 'David', 'Ashley'])
>>> print(employees.values())
dict_values([27, 35, 32, 28])

We can also extract key-value pairs as a list of tuples using the items() method:

>>> print(employees.items())
dict_items([('Max', 27), ('Jonathan', 35), ('David', 32), ('Ashley', 28)])

Dictionary Sorting by Key and Value

To sort a dictionary by keys or values, we first take the items (i.e. key-value pairs) and then use the key parameter of the sorted() function to choose either keys or values with indexing. Since an item is extracted as a tuple of a key and a value, the first element (with the index 0) is the key and the second element (with the index 1) is the value.

>>> sort by keys
>>> sorted(employees.items(), key=lambda item: item[0])
[('Ashley', 28), ('David', 32), ('Jonathan', 35), ('Max', 27)]

As we see in the output above, the final structure is a list of tuples, not a dictionary. This is because of the behavior of the sorted() function, which returns a list of tuples. If we want to have the final output as a dictionary, we simply apply the dict() constructor on the output of the sorted() function.

>>> sort by keys
>>> dict(sorted(employees.items(), key=lambda item: item[0]))
{'Ashley': 28, 'David': 32, 'Jonathan': 35, 'Max': 27}

Now the output is a dictionary. Remember that the original dictionary (i.e. employees) hasn’t been modified. Instead, we created a new dictionary with items sorted by keys. We can save it into a new variable.

Let’s now sort the employees dictionary by values.

>>> sort by values
>>> employees_sorted = dict(sorted(employees.items(), 
>>> key=lambda item: item[1]))
>>> print(employees_sorted)
{'Max': 27, 'Ashley': 28, 'David': 32, 'Jonathan': 35}

Dictionary Sorting by More Complex Criteria

By using a lambda function as an argument of the key parameter and having access to both keys and values, we can also specify more complex criteria for sorting. Let’s first create a new dictionary:

>>> employees = {
>>> "Max": {"Department": "Engineering", "Age": 27, "Starting Date": 2020},
>>> "David": {"Department": "Marketing", "Age": 32, "Starting Date": 2018},
>>> "Jonathan": {"Department": "HR", "Age": 35, "Starting Date": 2021},
>>> "Ashley": {"Department": "Marketing", "Age": 28, "Starting Date": 2019}
>>> }

In this new dictionary, each value is also a dictionary – so we have a dictionary in a dictionary, also known as a nested dictionary. We can sort the employees dictionary by one of the values in the nested dictionary.

The following example shows how to use the nested starting date values for sorting the employees dictionary:

>>> dict(sorted(employees.items(), 
>>> key=lambda item: item[1]["Starting Date"]))

{'David': {'Department': 'Marketing', 'Age': 32, 'Starting Date': 2018},
 'Ashley': {'Department': 'Marketing', 'Age': 28, 'Starting Date': 2019},
 'Max': {'Department': 'Engineering', 'Age': 27, 'Starting Date': 2020},
 'Jonathan': {'Department': 'HR', 'Age': 35, 'Starting Date': 2021}}

We can also sort by multiple values. In the following example, the lambda function creates a tuple of department and age values, which is then used for sorting the items in the employees dictionary. It first sorts by the department; employees in the same department are sorted by their age.

>>> dict(sorted(employees.items(),
>>> key=lambda item: (item[1]["Department"], item[1]["Age"])))

{'Max': {'Department': 'Engineering', 'Age': 27, 'Starting Date': 2020},
 'Jonathan': {'Department': 'HR', 'Age': 35, 'Starting Date': 2021},
 'Ashley': {'Department': 'Marketing', 'Age': 28, 'Starting Date': 2019},
 'David': {'Department': 'Marketing', 'Age': 32, 'Starting Date': 2018}}

Dictionary Sort Performance Issues

We always need to consider performance-related issues, as scalability is a fundamental concept in writing robust and efficient software programs. Time and operation complexity are the main things that affect sort performance.

The sorting operation may take a substantial amount of time if the data is large. Thus, it’s best to choose quicker and more performant methods if there are any. In our examples, we used lambda functions to extract the keys or values of items in a dictionary. We can also use the itemgetter function in the built-in operator module. It can be used for getting the first (index 0) or the second (index 1) element from dictionary items.

Let’s compare these two methods in a dictionary of 10 items. The first step is to create a dictionary:

>>> employees = {
>>>    "1001": 27,
>>>    "1002": 32,
>>>    "1003": 35,
>>>    "1004": 28,
>>>    "1005": 21,
>>>    "1006": 34,
>>>    "1007": 29,
>>>    "1008": 29,
>>>    "1009": 24,
>>>    "1010": 28
>>> }

We can measure the time of execution using the timeit module:

>>> from timeit import timeit
>>> stmt = 'dict(sorted(employees.items(), key=lambda item: item[1]))'
>>> timeit(stmt, globals=globals())
0.97 seconds

Let’s use the itemgetter function as the argument of the key parameter:

>>> from operator import itemgetter
>>> from timeit import timeit
>>> stmt = 'dict(sorted(employees.items(), key=itemgetter(1))'
>>> timeit(stmt, globals=globals())
0.79 seconds

With the itemgetter function, the sorting took approximately 19% less time. This may not sound like an important improvement when working on a dictionary of 10 items, but it will matter when the dataset gets large.