Sort Dictionary based on its values

How to sort a dictionary? It’s obvious to use the built-in sorted function, as it’s written in C and optimized already.

Note that dictionary cannot be ordered in Python, however tuples can, so one solution is to convert a dictionary to a list of tuples.

## Convert to Tuples

Start comparing the 0th elements first, then 1st elements, … So to compare dictionary, first convert it to a list of tuples, where the 0th element is value, 1st element is key

d_2_t = [(v,k) for (k,v) in data_dict]
sorted(d_2_t, reverse=True) Alternatively we can use the built-in zip function

d_2_t = list(zip(data_dict.values(), data_dict.keys()))
sorted(d_2_t, reverse=True)

## Sorted

Use the key parameter in sorted

temp = sorted(d.items(), key=lambda x:x, reverse=True)
res = {k:v for (k,v) in zip(range(1,len(temp)+1), temp.values())}

To build a rank dictionary, we can use enumerate. Note pass a 2nd parameter as the starting value

{d:(d, d) for d in enumerate(tmp,1)}
{% asset_img 'rank1.PNG' %}

To make the above python code more readable

{k:(idx, v) for idx, (k,v) in enumerate(tmp,1)} Reprint policy