sorting dictionary based on values code example
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: sort dict 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: sort dictionary
sorted(d.items(), key=lambda x: x[1])
sorted(d.items(), key=lambda x: x[1], reverse=True)
Example 4: sorting values in dictionary in python
d = {1: 1, 7: 2, 4: 2, 3: 1, 8: 1}
s=[]
for i in d.items():
s.append(i)
for i in range(0,len(s)):
for j in range(i+1,len(s)):
if s[i][1]<s[j][1]:
s[i],s[j]=s[j],s[i]
print(dict(s))