Python Notes

# Sorting Dictionary

In fact, the contents of the dictionary cannot be sorted, since the dictionary in Python is an unordered data structure.

It should be noted that in recent releases of Python, dictionaries remember the order in which entries are added to them. Thus, the dictionary can initially be populated with a sorted sequence of "key:value" pairs.

However, most often we are dealing with unordered dictionaries. When viewing the items of a dictionary, you can make it happen according to a certain order. For this purpose, an ordered structure is used, which can be sorted (a list or tuple).

## 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 = {'t': 4, 'm': 2, 'x': 3, 'a': 10}
>>> list_keys = list(d)
>>> list_keys
['t', 'm', 'x', 'a']
>>> list_keys.sort()
>>> list_keys
['a', 'm', 't', 'x']
>>> for i in list_keys:
...     print(i + ':', d[i])
...
a: 10
m: 2
t: 4
x: 3```

The `sorted()` function allows you to immediately create a list of sorted dictionary keys. So the example above is simplified to this:

```>>> d = {'t': 4, 'm': 2, 'x': 3, 'a': 10}
>>> for i in sorted(d):
...     print(i + ':', d[i])
...
a: 10
m: 2
t: 4
x: 3
```

## Sort by value

Sorting the dictionary by value is more difficult, since it is possible to access the entries 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.

```>>> d = {'t': 4, 'm': 2, 'x': 3, 'a': 10}
>>> list_d = list(d.items())
>>> list_d
[('t', 4), ('m', 2), ('x', 3), ('a', 10)]
>>> list_d.sort(key=lambda i: i)
>>> list_d
[('m', 2), ('x', 3), ('t', 4), ('a', 10)]
>>> for k, v in list_d:
...     print(k + ':', v)
...
m: 2
x: 3
t: 4
a: 10```

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.

You can also use the `sorted()` function:

```>>> d = {'t': 4, 'm': 2, 'x': 3, 'a': 10}
>>> t = sorted(d.items(), key=lambda i: i)
>>> t
[('m', 2), ('x', 3), ('t', 4), ('a', 10)]
```

## 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 = 20
>>> a
OrderedDict([(1, 10), (0, 5), (2, 20)])
>>> for i in a:
...     print(i, ':', a[i])
...
1 : 10
0 : 5
2 : 20```