Sort-Dictionary-By-Value
Sat 17 May 2025
title: "Sort Dictionary By Value" author: "Rj" date: 2019-04-20 description: "List Test" type: technical_note draft: false
dict = {
'one' : 8,
'two' : 1,
'three' : 12
}
dict
{'one': 8, 'three': 12, 'two': 1}
import operator
sorted_x = sorted(dict.items(), key=operator.itemgetter(1))
sorted_x
[('two', 1), ('one', 8), ('three', 12)]
type(sorted_x)
list
import collections
sorted_dict = collections.OrderedDict(dict)
sorted_dict
OrderedDict([('one', 8), ('two', 1), ('three', 12)])
# Reverse sort
reverse_dict= sorted(dict.items(), key=lambda x: x[1], reverse=True)
reverse_dict
[('three', 12), ('one', 8), ('two', 1)]
for x in reverse_dict:
print(x[0], "==>", x[1])
three ==> 12
one ==> 8
two ==> 1
Score: 10
Category: basics