Python Notes

Sorting Dictionary

In fact, the contents of the dictionary cannot be sorted, since the dictionary in Python is an unordered data structure. Even if you add elements to the dictionary in an orderly manner, for example alphabetically, they may appear differently when output.

However, when extracting items from the dictionary, you can make it happen according to a certain order. For this purpose, an ordered structure is used, which can be sorted. For example, a list.

Sort by keys

The easiest way to sort the dictionary by key. Algorithm for output dictionary contents:

  1. Create a list of dictionary keys.
  2. Sort it.
  3. In the for loop, iterate through the list items, using the list item as the dictionary key.
>>> d = {'a': 10, 'b': 15, 'c': 4}
>>> list_keys = list(d.keys())
>>> list_keys.sort()
>>> for i in list_keys:
...     print(i, ':', d[i])
... 
a : 10
b : 15
c : 4

Sort by value

Sorting the dictionary by value is more difficult, since it is possible to access the elements of the dictionary only by keys. However, you can create a list of tuples ("key", "value") and sort it by the second item of pairs. Further, the program uses this ordered structure, and not the original dictionary itself.

>>> d = {'a': 10, 'b': 15, 'c': 4}
>>> list_d = list(d.items())
>>> list_d
[('a', 10), ('b', 15), ('c', 4)]
>>> list_d.sort(key=lambda i: i[1])
>>> list_d
[('c', 4), ('a', 10), ('b', 15)]
>>> for i in list_d:
...     print(i[0], ':', i[1])
... 
c : 4
a : 10
b : 15

If we used the sort() method without the 'key' parameter, then the sorting would be performed by the first items of the tuples. The value for 'key' is the function. In this case, the lambda function is used, which reduces the amount of code. Tuples are passed to the function, and their second items are returned, by which sorting takes place.

OrderedDict class of collections module

The collections module has an OrderedDict class, which is a subclass of the dict class, that is, the usual Python dictionary. OrderedDict allows you to create dictionary objects that remember the order of their entries. The class also has a number of methods that can change the order of the entries in the dictionary.

>>> from collections import OrderedDict
>>> a = OrderedDict({1: 10, 0: 5})
>>> a
OrderedDict([(1, 10), (0, 5)])
>>> a[2] = 20
>>> a
OrderedDict([(1, 10), (0, 5), (2, 20)])
>>> for i in a:
...     print(i, ':', a[i])
... 
1 : 10
0 : 5
2 : 20