# The Ranked Dict

> Values deserve order too.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a dict with string keys and numeric values, return a new dict with entries sorted by value descending (tie-break by key alphabetically). Use Python's insertion-order-preserving dict semantics to present the sorted order.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **sorting dictionary entries by value** and reconstructing a dict in that order. It checks whether candidates understand that Python 3.7+ dicts preserve insertion order, making sorted reconstruction meaningful.

---

### Break down the requirements

#### Step 1: Extract key-value pairs

Convert the dictionary into a list of (key, value) tuples for sorting.

#### Step 2: Sort by value descending

Sort the pairs by the second element in descending order.

#### Step 3: Rebuild the dict in sorted order

Insert pairs into a new dict in the sorted order. Python 3.7+ preserves this insertion order.

---

### The solution

**Sort pairs by value, rebuild ordered dict**

```python
def ranked_dict(d):
    pairs = []
    for key in d:
        pairs.append((key, d[key]))
    pairs.sort(key=lambda p: p[1], reverse=True)
    result = {}
    for key, val in pairs:
        result[key] = val
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n log n) for sorting.
> 
> **Space:** O(n) for the pairs list and result dict.

> **Interviewers Watch For**
>
> Do you know that Python dicts preserve insertion order since 3.7? This is what makes the rebuilt dict meaningful. In older Python versions, you would need `collections.OrderedDict`.

> **Common Pitfall**
>
> Sorting by keys instead of values. The lambda `key=lambda p: p[1]` sorts by the second tuple element (the value), not the first (the key).

---

## Common follow-up questions

- What if values are equal and you need secondary sort by key? _(Tests adding a second element to the sort key tuple.)_
- What if you only need the top 3 entries? _(Tests slicing after sorting or using a heap.)_
- How would you handle non-comparable values? _(Tests that sorting fails on mixed types and how to handle that.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_ranked_dict)
- [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.