Sort Dictionary by Keys or Values in Python

A dictionary is a data structure that uses the key:value pairs and can be written in the following way:

You can also use a dictionary constructor to create a dictionary:

If you run the code, you’ll notice that both values and keys are not sorted by default, and they appear in the order they were inserted.

dog >> woof 
pig >> oink 
horse >> neigh 
cat >> meow

It doesn’t matter whether you use integers or strings for keys and values, the sorting works in a similar way. For text, the order will be from A to Z, and for numbers from the smallest number to the largest.

In this lesson, I’ll also show you how to order keys and values in descending order.

Print Dictionary Keys in a Sorted Way

The sorted function

The easiest way is to use the sorted function.

The result is sorted alphabetically by key:

cat >> meow
dog >> woof
horse >> neigh
pig >> oink

The problem with this approach is that you can’t sort and store the dictionary this way in a new dictionary. It’s only useful to print its keys in an ordered list, and not assign the ordered version to a new directory.

This code is correct but doesn’t do what is intended. It won’t assign a sorted animal directory to ordered_animals. It will create a list from the sorted keys. If this is what you want, you can use it.

{'dog': 'woof', 'pig': 'oink', 'horse': 'neigh', 'cat': 'meow'}
['cat', 'dog', 'horse', 'pig']
<class 'dict'>
<class 'list'>

Data pretty printer

Another way to bring the ordered list to the console is to use the pprint module.

The pprint works the same way as print, but displays a dictionary in an ordered form.

{'dog': 'woof', 'pig': 'oink', 'horse': 'neigh', 'cat': 'meow'}
{'cat': 'meow', 'dog': 'woof', 'horse': 'neigh', 'pig': 'oink'}

The collections library for Python 3.2+

You can assign a sorted dictionary to a new one using the OrderedDict subclass. First, you need to import it from the collections library.

Now, you can assign the animals directory to a new one called ordered_animals.

If you run the code, you’ll notice that the new dictionary is ordered.

cat >> meow
dog >> woof
horse >> neigh
pig >> oink

Run this code to check the types of objects.

The returned class is collections and the subclass is OrderedDict.

OrderedDict([('cat', 'meow'), ('dog', 'woof'), ('horse', 'neigh'), ('pig', 'oink')])
<class 'collections.OrderedDict'>

If you use OrderedDict when creating the animals dictionary, it won’t return the ordered directory.

Run the code to see the result.

dog >> woof
pig >> oink
horse >> neigh
cat >> meow

The result is in the same order as the order of entered values.

Easy sorting for Python 3.7+

If you use Python 3.7 or higher, you can modify this code. Instead of using SortedDict, you can use dict. There is no need of importing an additional library.

The result is the same as before – the sorted dictionary.

cat >> meow
dog >> woof
horse >> neigh
pig >> oink

You can run the type function to see that ordered_animals is a dict.

<class 'dict'>

Convert Directory to a Sorted List with Itemgetter

Another way to create a sorted list is to use itemgetter.

First, you need to import itemgetter from the operator module.

This operator takes 0 as an argument. This means that the list has to be sorted for keys. Then the whole dictionary is transformed into a list of tuples.

[('cat', 'meow'), ('dog', 'woof'), ('horse', 'neigh'), ('pig', 'oink')]
<class 'list'>
<class 'tuple'>

The ordered_animals list is ordered by the key part.

If you run the type method, you can check that the ordered_animals is indeed a list, and a single element of this list is a tuple.

Sort a Dictionary by Values

So far, I showed you a few different methods to sort the key part of a dictionary, but there is also the second part of a dictionary: value. Sometimes, you need to sort it too.

Display Dictionary Values in the Sorted Manner

This example uses the FOR loop to display sorted directory values. It doesn’t require an additional import.

The reverse parameter is set to False, therefore the value is displayed in ascending order.

cat >> meow
horse >> neigh
pig >> oink
dog >> woof

Change reverse to True and the sorting will be reversed.

dog >> woof
pig >> oink
horse >> neigh
cat >> meow

itemgetter

The quickest way to sort a dictionary is to use the example from the previous step and change the itemgetter argument to 1.

If you run the code, you’ll notice that it’s sorted by the second part of the tuple:

[('cat', 'meow'), ('horse', 'neigh'), ('pig', 'oink'), ('dog', 'woof')]

Lambda for Python 3.7+

In Python 3.7, you can use the lambda function to create a sorted directory by values.

With type you can check that ordered_animals is a directory sorted by values.

{'cat': 'meow', 'horse': 'neigh', 'pig': 'oink', 'dog': 'woof'}
<class 'dict'>

If you want to create a dictionary sorted in reversed order, add an additional argument, that is set to false by default, to reverse=True.

Now, the dictionary value is sorted in descending order.

{'dog': 'woof', 'pig': 'oink', 'horse': 'neigh', 'cat': 'meow'}