A dictionary is a data structure that uses the key:value pairs and can be written in the following way:
1 |
animals = {'dog': 'woof', 'pig': 'oink', 'horse': 'neigh', 'cat': 'meow'} |
You can also use a dictionary constructor to create a dictionary:
1 2 3 4 |
animals = dict(dog='woof', pig='oink', horse='neigh', cat='meow') for x in animals: print(x, '>>', animals[x]) |
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.
1 2 3 4 |
animals = dict(dog='woof', pig='oink', horse='neigh', cat='meow') for x in sorted(animals): print(x, '>>', animals[x]) |
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.
1 2 3 4 5 6 7 |
animals = dict(dog='woof', pig='oink', horse='neigh', cat='meow') ordered_animals = sorted(animals) print(animals) print(ordered_animals) print(type(animals)) print(type(ordered_animals)) |
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.
1 2 3 4 5 |
from pprint import pprint animals = dict(dog='woof', pig='oink', horse='neigh', cat='meow') print(animals) pprint(animals) |
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.
1 2 3 4 5 6 7 |
from collections import OrderedDict animals = dict(dog='woof', pig='oink', horse='neigh', cat='meow') ordered_animals = OrderedDict(sorted(animals.items())) for x in ordered_animals: print(x, '>>', ordered_animals[x]) |
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.
1 2 |
print(ordered_animals) print(type(ordered_animals)) |
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.
1 2 3 4 5 6 |
from collections import OrderedDict animals = OrderedDict(dog='woof', pig='oink', horse='neigh', cat='meow') for x in animals: print(x, '>>', animals[x]) |
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.
1 2 3 4 5 6 |
animals = dict(dog='woof', pig='oink', horse='neigh', cat='meow') ordered_animals = dict(sorted(animals.items())) for x in ordered_animals: print(x, '>>', ordered_animals[x]) |
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.
1 2 3 4 5 6 7 8 |
from operator import itemgetter animals = dict(dog='woof', pig='oink', horse='neigh', cat='meow') ordered_animals = sorted(animals.items(), key=itemgetter(0)) print(ordered_animals) print(type(ordered_animals)) print(type(ordered_animals[0])) |
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.
1 2 3 4 |
animals = dict(dog='woof', pig='oink', horse='neigh', cat='meow') for k in sorted(animals, key=animals.get, reverse=False): print(k, '>>', animals[k]) |
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.
1 2 3 4 5 6 |
from operator import itemgetter animals = dict(dog='woof', pig='oink', horse='neigh', cat='meow') ordered_animals = sorted(animals.items(), key=itemgetter(1)) print(ordered_animals) |
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.
1 2 3 4 5 |
animals = dict(dog='woof', pig='oink', horse='neigh', cat='meow') ordered_animals = dict(sorted(animals.items(), key=lambda x: x[1])) print(ordered_animals) print(type(ordered_animals)) |
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.
1 |
ordered_animals = dict(sorted(animals.items(), key=lambda x: x[1], reverse=True)) |
Now, the dictionary value is sorted in descending order.
{'dog': 'woof', 'pig': 'oink', 'horse': 'neigh', 'cat': 'meow'}