In Python 3.7+ it’s 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:

**Create**a dictionary of key-value pairs.**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 example, let’s sort a dictionary by values in descending order and print out the sorted values:

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])

This gives a following output:

Alice 72 Charlie 36 Bob 23 Eric 18 David 9

This is a comprehensive guide to sorting dictionaries in Python. 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

Besides, you will 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)

Let’s take a closer look at the arguments of the **sorted()** function:

**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 the
**reverse**is True, sorting happens in descending order. - If the
**reverse**is**False**, sorting happens in ascending order.

- If the
**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. The idea of a dictionary is to store values accessible via keys, instead of indices like in lists. This makes dictionaries great data stores for labeled and structured data.

For instance, you might have a dictionary that represents the students of a class. Each student can be associated with data like name, age, grades, and so on.

Anyway, the point of this guide is not to teach what a dictionary is but how to sort it. More specifically, you will now see how to sort dictionaries in Python in:

- Ascending order
- Descending order

To sort a dictionary **by values**, you need to let the **sorted()** function know it. 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 in the function call.

**The key parameter acts as the sorting function.** In other words, the **sorted()** performs a built-in sorting algorithm on the elements of the list and calls the **key** function for each element to sort them in the desired way.

To sort in ascending order, the **key** function is trivial. It just needs to do is take a key-value pair as an input and return the value as an output. To create such a function, you can use a lambda function.

Let’s see some examples.

### Sort by Values: Ascending Order

For example, given a data dictionary of student names mapped to their ages, let’s sort the dictionary data in ascending age order.

By the way, the **sorted()** function doesn’t return a dictionary. It returns a list of tuples that represent the dictionary keys and values. To turn the result into a dictionary, you need to call the **dict()** function on it.

Here is the code:

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}

To make sure you understand what’s going on, later in this guide, you will take a deeper look at the **key=lamda x: x[1]** part and how it works. For now, let’s continue sorting.

### Sort by Values: Descending Order

In the previous example, you saw how to sort dictionary values in ascending order. This time, let’s repeat the example, but instead of ascending, let’s sort the values in descending order.

To sort in descending order, specify set the **reverse** parameter **True**.

Here is how it looks in code:

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}

Next, let’s take a look at sorting dictionaries by keys.

## How to Sort a Dictionary by Key

To sort a dictionary by keys in Python, call the **sorted()** function on dictionary items.

By the way, 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 some examples of sorting the keys in both ascending and descending order.

### Example 1: 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}

### Example 2: 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 understanding how dictionary sorting truly works in the above examples because of the lambda expressions?

This chapter focuses on the details of the parameters in the **sorted()** function.

At the end of this section, you’ll understand better what this type of call actually does:

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

Let’s start with the first argument, that is, **dict.items()**.

### Argument 1: dict.items()

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

dict["somevalue"]

But 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’s:

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

To do this, there is a built-in method **dictionary.items()**.

**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. This is probably the most confusing part of the **sorted()** function call. It requires quite a bit of explanation for you to fully understand what’s going on.

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

The **key** parameter is an optional parameter in the **sorted()** function. It acts as the sorting function that the algorithm behind the scenes runs on each element of the dictionary.

When sorting dictionaries, the default way of sorting is by keys. To change the sorting method, you need to tell the **sorted()** function you want to use values instead.

To communicate with the **sorted()** function, you need to specify the **key** parameter, which is the sorting function. To do sorting by values, the sorter has to take a key-value pair from a dictionary and return its value.

**You can use a regular function to do this.**

For example, here is a function that takes a key-value pair and returns the value:

def getvalue(pair): return pair[1]

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

For example, let’s sort a dictionary of names and ages by ages (that is, by values):

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}

Now, let’s take a closer look at how and why this works. 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 sorting dictionaries.

Next, let’s take a look at some best practices and lambda functions.

#### Use Lambdas Instead of Traditional Functions

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

In the previous example, you only use the **getvalue** function once. This means after sorting, you leave a useless function definition hanging in your codebase. That’s not ideal.

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 a lambda function in Python is generally:

lambda arguments : expression

Here the **arguments** are nothing but traditional function arguments, and the **expression** is a line of Python code that runs a function given the arguments returns a result.

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

So you have a traditional **getvalue** function that looks like this:

def getvalue(pair): return pair[1]

Now, let’s convert this to a lambda expression:

lambda pair : pair[1]

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

But because a lambda does not have a name, you cannot refer to it in any way. In other words, the lambda expression is useless as a standalone expression like seen above.

To be able to use lambda, you need to **call it right away.** Because of this, you commonly use lambda functions as arguments in other function calls.

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

Instead of separately specifying a **getvalue** function, use the lambda expression:

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)

In a sense, you now implemented the **getvalue** function directly into the **sorted() **function call and used it right away.

Here is the 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}

The above dictionary is sorted such that the ages of odd numbers appear first and the ages of even values last. Another way to think of it is that the age data is sorted such that the “evenness” grows the further right you go. This is why the odd values come first and the even values follow.

**If you did not know about lambdas before reading this article, I highly recommend reading Lambdas in Python to get a better understanding of this important concept.**

### Argument 3: 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!