# The Value Sorter

> The order was always negotiable.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

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

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **custom sorting** with a composite key. Sorting by value descending with alphabetical tiebreaker probes whether a candidate can construct the right sort key to achieve multi-criteria ordering.

---

### Break down the requirements

#### Step 1: Convert the dict to a list of tuples

Extract `(key, value)` pairs for sorting.

#### Step 2: Sort by value descending, then key ascending

Use a composite sort key that negates the value for descending order and uses the key for alphabetical tiebreaking.

---

### The solution

**Composite sort key with negation trick**

```python
def sort_by_value(d: dict) -> list:
    pairs = []
    for key, value in d.items():
        pairs.append((key, value))
    pairs.sort(key=lambda x: (-x[1], x[0]))
    return pairs
```

> **Time and Space Complexity**
>
> **Time:** O(n log n) for sorting where n is the number of dict entries.
> 
> **Space:** O(n) for the pairs list.

> **Interviewers Watch For**
>
> The negation trick `(-x[1], x[0])` for descending numeric sort combined with ascending string sort in a single `sort` call. This is a Python idiom that shows fluency.

> **Common Pitfall**
>
> Using `reverse=True` on the sort. This reverses ALL criteria, making the alphabetical tiebreaker Z-to-A instead of A-to-Z.

---

## Common follow-up questions

- What if values could be strings and you needed case-insensitive sorting? _(Tests normalizing with `.lower()` in the sort key.)_
- What if you only needed the top 5 entries? _(Tests `heapq.nlargest` for O(n log 5) instead of full sort.)_
- How would you handle float values where negation might cause precision issues? _(Tests that negation of floats is exact in IEEE 754 and does not introduce errors.)_

## Related

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