The Value Sorter

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
Pacific Gas and Electric Company

Problem

Given a dict, return a list of [key, value] pairs (each pair is a two-element list) sorted by value descending, tie-break alphabetically by key ascending.

The order was always negotiable.

Example

Input:

d = {"apples":5,"bananas":2,"oranges":8}

Output:

[["oranges",8],["apples",5],["bananas",2]]

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 [key, value] pairs

Extract each [key, value] pair from the dict into a list so the result is a list of two-element lists.

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
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

Common follow-up questions