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
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 pairsCommon 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.)