Sort a dictionary by value

EasyDictionary Programs · 12 of 94

Write a Python program to sort a dictionary by its values.

Advertisement
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

  1. key=lambda kv: kv[1].

Solution

Python
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.

More dictionary programs

← All 94 Dictionary Programs

Leave a Comment