Example 1: how to sort a dictionary by value in python
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
Example 2: python dict sort by value
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Example 3: python - sort dictionary by value
d = {'one':1,'three':3,'five':5,'two':2,'four':4}
a = sorted(d.items(), key=lambda x: x[1])
r = sorted(d.items(), key=lambda x: x[1], reverse=True)
Example 4: python get dictionary keys sorted by value
sorted(A, key=A.get)
Example 5: Python sort dictionary by value
from operator import itemgetter
new_dict = sorted(data.items(), key=itemgetter(1))
Example 6: sort a dictionary by value then key
d = {'apple': 2, 'banana': 3, 'almond':2 , 'beetroot': 3, 'peach': 4}
[v[0] for v in sorted(d.items(), key=lambda kv: (-kv[1], kv[0]))]