Python Practice › Dictionary Programs › Program 12
Sort a dictionary by value
Write a Python program to sort a dictionary by its values.
Input
{"d": 14, "b": 52, "a": 13, "c": 1}Output
[('c', 1), ('a', 13), ('d', 14), ('b', 52)]
{'b': 52, 'd': 14, 'a': 13, 'c': 1}Approach
key=lambda kv: kv[1].
Solution
d = {"d": 14, "b": 52, "a": 13, "c": 1}print(sorted(d.items(), key=lambda kv: kv[1]))print(dict(sorted(d.items(), key=lambda kv: kv[1], reverse=True)))Output
[('c', 1), ('a', 13), ('d', 14), ('b', 52)]
{'b': 52, 'd': 14, 'a': 13, 'c': 1}Learn the concept
New to this topic? Read the lesson, then come back.