# Rank Metrics

> Not all numbers are equal. Rank them.

Canonical URL: <https://datadriven.io/problems/rank_metrics>

Domain: Python · Difficulty: medium · Seniority: L3

## Problem

Given a dict, return a list of [key, value] pairs sorted by value descending, tie-break by key ascending.

## Worked solution and explanation

### Why this problem exists in real interviews

Sorting key-value pairs by value tests whether you can use **custom sort keys** and handle the descending order correctly. It is a common reporting pattern.

---

### Break down the requirements

#### Step 1: Accept a dict or list of key-value pairs

The input maps metric names to their values.

#### Step 2: Sort by value in descending order

Use a sort key that extracts the value, with `reverse=True`.

---

### The solution

**Custom-key sort on value with descending order**

```python
def rank_metrics(metrics):
    pairs = []
    for key in metrics:
        pairs.append([key, metrics[key]])
    sorted_pairs = sorted(pairs, key=lambda x: x[1], reverse=True)
    return sorted_pairs
```

> **Time and Space Complexity**
>
> **Time:** O(n log n) for the sort where n is the number of metrics.
> 
> **Space:** O(n) for the pairs list and sorted result.

> **Interviewers Watch For**
>
> Using `sorted()` with a key function and `reverse=True` rather than negating values or sorting then reversing. The key+reverse approach is the most Pythonic.

> **Common Pitfall**
>
> Sorting by key instead of value. Double-check which element of the pair is the sort criterion.

---

## Common follow-up questions

- What if you only need the top-k metrics? _(Tests using `heapq.nlargest(k, metrics.items(), key=lambda x: x[1])` for O(n log k) performance.)_
- How would you handle ties? _(Tests adding a secondary sort key (e.g., alphabetical by name) for deterministic output.)_
- What if the metrics dict is updated frequently? _(Tests maintaining a sorted structure like a SortedDict or a heap.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/rank_metrics)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.