order dict by value python 3 code example

Example 1: python sort dictionary by value descending

Python Code:
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = dict(sorted(d.items(), key=operator.itemgetter(1)))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = dict(sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in descending order by value : ',sorted_d)

Sample Output:
Original dictionary :  {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Dictionary in ascending order by value :  {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Dictionary in descending order by value :  {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}

Example 2: 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))


# Sort by key
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

Example 3: python - sort dictionary by value

d = {'one':1,'three':3,'five':5,'two':2,'four':4}

# Sort
a = sorted(d.items(), key=lambda x: x[1])

# Reverse sort
r = sorted(d.items(), key=lambda x: x[1], reverse=True)