Python DICTionary HowTo (Page: 3)
How to sort dictionary in Python
Dictionary is an unsorted object and it is a common task to sort it. It is possible to imagine few different way of sorting it. Sorting by key, sorting by value and combination of sorting by key and value. Let’s consider all these cases
Sorting dictionary by key
It is possible to sort Python dictionary by its key with function sorted(). It is important to make sure that all keys are the same type
in this example all keys are int
d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items())
print( type(sd)) # class 'list'
print(sd) #[(1, 89), (2, 3), (3, 0), (4, 5)]
for k,v in sd: print(k,':', v, end='; ') # 1 : 89; 2 : 3; 3 : 0; 4 : 5;
This code will also work for other compatible types of keys. As a result, two dimensional array (list of pairs key, value) will be produced
Sorting dictionary by key in reversed order
It is possible to sort in key reversed order.
d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items(), reverse=True)
for k,v in sd: print(k,':', v, end='; ') # 4 : 5; 3 : 0; 2 : 3; 1 : 89;
Sorting dictionary by value
Another task is to sort dictionary by it’s value. This is a bit more complicates procedure. We need to use lambda function to do this
d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items(), key=lambda x: x[1]) # can add reverse=True
for k,v in sd: print(k,':', v, end='; ') # 3 : 0; 2 : 3; 4 : 5; 1 : 89;
Sorting dictionary by key and value
lambda function is a very powerful mechanism, which allow us to do any type of sorting. Now we will sort Python dictionary by its value, but for pairs with identical value, we will perform key sort as well
Sorting value - key order
d = {'abc': 14, 'awc': 13, 'aac': 12, 'adc': 13}
sd = sorted(d.items(), key=lambda x: (x[1], x[0]))
for k,v in sd: print(k,':', v, end='; ') # aac : 12; adc : 13; awc : 13; abc : 14;
Sorting key - value order
This example is senseless, because all keys are unique and sorting buy keys will be unique. This example shown only as an example of the syntax.
d = {'abc': 14, 'awc': 13, 'aac': 12, 'adc': 13}
sd = sorted(d.items(), key=lambda x: (x[0], x[1]))
for k,v in sd: print(k,':', v, end='; ') # aac : 12; abc : 14; adc : 13; awc : 13;
and this code will be equivalent to
d = {'abc': 14, 'awc': 13, 'aac': 12, 'adc': 13}
sd = sorted(d.items(), key=lambda x: (x[0]))
for k,v in sd: print(k,':', v, end='; ') # aac : 12; abc : 14; adc : 13; awc : 13;
But for key sorting it is easier to use first solution in this section.
Published: 2021-10-13 14:31:51
Updated: 2021-10-20 14:27:27