Sort a Dict by Value

Medium ⏱ 12 min 64% acceptance ★★★★★ 4.5
Write a function sort_by_value(d, descending=False) that returns a list of (key, value) tuples from dict d, sorted by value. Sort ascending by default; if descending is True, sort from highest to lowest value. Break ties by key ascending.

Examples

Example 1
Input
sort_by_value({'a': 3, 'b': 1, 'c': 2})
Output
[('b', 1), ('c', 2), ('a', 3)]
Explanation

Ascending by value.

Example 2
Input
sort_by_value({'a': 3, 'b': 1, 'c': 2}, descending=True)
Output
[('a', 3), ('c', 2), ('b', 1)]
Explanation

Descending by value.

Constraints

  • Ties broken by key ascending in both modes.

Topics

Dictionariessorting

Companies

FlipkartWalmart

Hints

Hint 1

`sorted(d.items(), key=lambda kv: (kv[1], kv[0]))`, then reverse only the value part if descending via a negated sort key or `reverse=True` (careful with tie order).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.