In Python 3.7+ it is possible to sort a dictionary. Before Python 3.7 dictionaries were unordered and thus you could not sort them.

To sort a dictionary in Python:

**Specify**a dictionary.**Decide**whether you want to sort by keys or values.**Choose**between ascending and descending order.**Call**the built-in**sorted()**function on the dictionary items.

For instance, let’s sort a dictionary by values in descending order:

data = { "Bob": 23, "Charlie": 36, "Alice": 72, "Eric": 18, "David": 9 } sort_data = sorted(data.items(), key=lambda x: x[1], reverse=True) for i in sort_data: print(i[0], i[1])

Output:

Alice 72 Charlie 36 Bob 23 Eric 18 David 9

In this guide, you learn how to sort a dictionary:

- By keys
- In ascending order
- In descending order

- By values
- In ascending order
- In descending order

In addition, you are going to take a deep dive into the arguments of the **sorted() **function to truly understand how it works.

## Python Sorted() Function

In Python, there is a built-in** sorted() **function you can use to sort iterables, such as lists or dictionaries.

The syntax of the **sorted()** function is:

sorted(iterable, key=None, reverse=False)

Where:

**iterable**is a sequence or collection of values (such as list, dict, string) to be sorted.**reverse**is an optional parameter. By default, the**reverse**is**False**.- If
**True**, sorting happens in descending order. - If
**False**, sorting happens in ascending order.

- If
**key**is an optional parameter. It provides a sorting function by which the elements are sorted.

Let’s see the **sorted()** function in action by sorting a dictionary in a bunch of different ways.

## How to Sort a Dictionary by Value

In Python, a dictionary is a collection of key-value pairs.

Let’s see how to sort a dictionary by values in:

- Ascending order
- Descending order

To sort a dictionary by values, you need to let the **sorted()** function know that. This is because, by default, the **sorted()** function sorts a dictionary by keys.

To let the **sorted()** function know you want to sort the dictionary by values, specify the optional **key** parameter, which acts as the sorting function.

In this case, the sorting function is simple. All it needs to do is take a key-value pair and return the value. This can be done using a lambda function.

### Ascending Order

For example, let’s sort a dictionary of name-age data by ages in ascending order:

data = { "Bob": 23, "Charlie": 36, "Alice": 72, "Eric": 18, "David": 9 } sort_data = sorted(data.items(), key=lambda x: x[1]) sort_data_dict = dict(sort_data) print(sort_data_dict)

Output:

{'David': 9, 'Eric': 18, 'Bob': 23, 'Charlie': 36, 'Alice': 72}

### Descending Order

For example, let’s sort a dictionary of name-age data by ages in descending order:

data = { "Bob": 23, "Charlie": 36, "Alice": 72, "Eric": 18, "David": 9 } sort_data = sorted(data.items(), key=lambda x: x[1], reverse=True) sort_data_dict = dict(sort_data) print(sort_data_dict)

Output:

{'Alice': 72, 'Charlie': 36, 'Bob': 23, 'Eric': 18, 'David': 9}

## How to Sort a Dictionary by Key

To sort a dictionary by keys in Python, call the **sorted()** function on dictionary items. The **sorted()** function sorts a dictionary by keys by default, so this is a bit easier than sorting by values.

For the sake of completeness, let’s see examples of sorting in both ascending and descending order.

### Ascending Order

For example, let’s sort a dictionary of name-age data by names in ascending (alphabetical) order:

data = { "Bob": 23, "Charlie": 36, "Alice": 72, "Eric": 18, "David": 9 } sort_data = sorted(data.items()) sort_data_dict = dict(sort_data) print(sort_data_dict)

Output:

{'Alice': 72, 'Bob': 23, 'Charlie': 36, 'David': 9, 'Eric': 18}

### Descending Order

For example, let’s sort a dictionary of name-age data by names in descending (reverse-alphabetical) order:

data = { "Bob": 23, "Charlie": 36, "Alice": 72, "Eric": 18, "David": 9 } sort_data = sorted(data.items(), reverse=True) sort_data_dict = dict(sort_data) print(sort_data_dict)

Output:

{'Eric': 18, 'David': 9, 'Charlie': 36, 'Bob': 23, 'Alice': 72}

Now you understand how to sort a dictionary in Python.

Next, let’s take a deeper dive into the arguments of the **sorted()** function call. If you understood everything thus far, feel free to skip this chapter.

## The sorted() Function Parameters: A Detailed Look

Did you have difficulties in understanding how dictionary sorting truly works in the above examples?

There was a bunch of function calls that looked something like this:

sorted(dict.items(), key=lambda x: x[1], reverse=True)

If you are a beginner, or for example not familiar with lambdas, these arguments might look daunting to you.

To truly understand how sorting a dictionary works, let’s take a closer look at these parameters.

### dict.items()

When dealing with dictionaries in Python, you can access the key-value pairs using the square bracket accessing operator [].

dict["somevalue"]

However, when it comes to looping through a dictionary, you cannot directly use the dictionary as-is.

Instead, you need to convert the dictionary objects to a sequence of tuples, where each tuple the:

- First element is the key.
- Second element is a pair.

In Python, there is a built-in method **dictionary.items()** you can use to make this conversion.

To take home: Whenever you want to loop through a dictionary, you can only access the key-value data via the **dictionary.items()** method.

The same applies to sorting a dictionary using the **sorted()** function.

The **sorted()** function performs looping under the hood, so instead of giving the dictionary, you need to provide it with a sequence of key-value tuples to work with. So use **dictionary.items()**.

Next, let’s take a look at the lambda argument.

### key=lambda x: x[1]

The **key** parameter is an optional parameter in the **sorted()** function.

It acts as the sorting function.

When sorting dictionaries, the sorting is made by keys by default. The only way to change this is by letting the **sorted()** function know you want to use values instead.

To do this, the sorting function (**key** parameter) needs to take a key-value pair from a dictionary and return the value of it.

You can use a regular function to do this.

All the function needs to do is to take a key-value pair (a tuple) as an argument and return the value from it.

Here is an example implementation:

def getvalue(pair): return pair[1]

Now, you can use this function as the **key** parameter in the **sorted()** function call.

For example:

data = { "Bob": 12, "Charlie": 7, "Alice": 18, } def getvalue(pair): return pair[1] sort_data = sorted(data.items(), key=getvalue) sort_data_dict = dict(sort_data) print(sort_data_dict)

Output:

{'Charlie': 7, 'Bob': 12, 'Alice': 18}

But how does this work?

Under the hood, the **sorted()** function:

- Loops through each key-value pair.
- Takes the pairs one by one and calls the
**getvalue**function for each pair. - Sorts the data based on what the
**getvalue**function returns.

In this case, the function returns the value, so the **sorted() **function looks at each value and sorts the dictionary based on the values.

Now you have a better understanding of how the** key** function works.

When it comes to best practices, specifying a separate function introduces unnecessary lines of code.

In the above example, you only use the **getvalue** function once. This means after sorting, you leave a useless function definition hanging in your codebase. Doing this is against best practices.

This is where **lambda functions** help.

**A lambda function** is an anonymous function that has no name. It can take any number of arguments but only have a single expression.

You can specify a lambda function to replace simple one-expression functions in situations like this.

The syntax of lambda is:

lambda arguments : expression

Here the **arguments** are regular function arguments, and the **expression** is a line of Python code that operates on the arguments and returns a result.

To demonstrate how lambdas work, let’s convert the **getvalue** function into a lambda expression.

So we have a function like this:

def getvalue(pair): return pair[1]

When converted to lambda, it looks like this:

lambda pair : pair[1]

This lambda expression works exactly the same way as the **getvalue** function.

However, because a lambda does not have a name, you cannot refer to it in any way. This means a lambda expression is useless as a standalone expression.

To be able to use the lambda, you need to call it right away. You can for example pass it as an argument to another function.

Now, let’s go back to sorting a dictionary.

Instead of separately specifying the **getvalue** function, you can pass the lambda expression directly as the **key** argument:

data = { "Bob": 12, "Charlie": 7, "Alice": 18, } sort_data = sorted(data.items(), key=lambda pair : pair[1]) sort_data_dict = dict(sort_data) print(sort_data_dict)

Output:

{'Charlie': 7, 'Bob': 12, 'Alice': 18}

Using a lambda this way you can make the code shorter and of better quality.

Notice that you can name the lambda arguments however you want to. You do not need to use the word **pair**. Instead, you can simply use **x** as we did earlier in this guide.

sort_data = sorted(data.items(), key=lambda x : x[1])

Now you understand how the **key** function works in the **sorted()** function call.

One more thing about the **key** function: The **key** function can be a more complex function too.

For instance, let’s sort the dictionary by checking if the age value is even (divisible by 2):

data = { "Bob": 12, "Charlie": 7, "Alice": 18, "David": 3} sort_data = sorted(data.items(), key=lambda pair : pair[1] % 2 == 0) sort_data_dict = dict(sort_data) print(sort_data_dict)

Output:

{'Charlie': 7, 'David': 3, 'Bob': 12, 'Alice': 18}

Now the dictionary is sorted such that ages of odd numbers are first and evens last. In a sense, the “evenness” of the age is sorted such that it grows the further right we go in the dictionary. This is why the odd values come first.

If you did not know about lambdas before reading this article, I highly recommend checking this article to get a full picture:

### reverse=True

The **reverse** argument is the third argument in the **sorted() **function call. This is an optional argument. It specifies the order in which the sorting is done.

By default, the **reverse** argument is **False**.

This means the sorting order is ascending by default.

However, to change the direction, you can set the **reverse** argument **True**.

Awesome! Now you understand how the **sorted()** function really works.

Finally, let’s take a look at how sorting a dictionary is done in Python versions less than 3.7.

## Sorting Dictionaries Before Python 3.7

Before Python 3.7, dictionaries are orderless. This means sorting is a meaningless operation because the data will be out of order anyway.

However, other data types such as lists and tuples are ordered. Furthermore, there is a separate data type for sorted dictionaries called **OrderedDict**.

This means you could sort a dictionary by following these steps:

**Grab**the key-value pairs.**Sort**the key-value pairs. This gives you a sorted list of tuples.**Insert**the sorted list of tuples into an**OrderedDict**.

Here is an example:

from collections import OrderedDict data = { "Bob": 23, "Charlie": 36, "Alice": 72, "Eric": 18, "David": 9 } sort_data = sorted(data.items(), key=lambda x: x[1]) sort_data_dict = OrderedDict(sort_data) print(sort_data_dict)

Output:

OrderedDict([('David', 9), ('Eric', 18), ('Bob', 23), ('Charlie', 36), ('Alice', 72)])

You can access the **OrderedDict** object elements the same way you would use a regular dictionary.

## Conclusion

Today you learned how to sort a dictionary in Python.

To recap, as of Python 3.7, dictionaries preserve the insertion order. In other words, you can sort a dictionary.

To sort a dictionary, use the built-in **sorted() **function by giving it the following arguments:

**iterable**. The dictionary items.**key**. The sorting function.**reverse**. If you want to reverse the sort.

Thanks for reading.

Happy coding!