Sort items in descending order of value

EasyDictionary Programs · 46 of 94

Write a Python program to sort a dictionary’s items by value, highest first.

Advertisement
Input
{"Math": 70, "Physics": 90, "Chemistry": 67}
Output
{'Physics': 90, 'Math': 70, 'Chemistry': 67}

Approach

  1. sorted(..., key=..., reverse=True).

Solution

Python
d = {"Math": 70, "Physics": 90, "Chemistry": 67}print(dict(sorted(d.items(), key=lambda kv: kv[1], reverse=True)))
Output
{'Physics': 90, 'Math': 70, 'Chemistry': 67}

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs

Leave a Comment