The Wide View
A hard Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- hard
- Seniority
- L4
Problem
A reporting export arrives in long format: one record per cell, each carrying a row label, a col label, and a numeric val. Reshape it into a nested lookup keyed by row then column, so result[row][col] returns that cell's value. Rows are sparse, holding only the columns that actually appear for them, and when the same row and column pair shows up more than once the later record wins.
Long format is easy. Wide format is useful.
Example 1
Input:
records = [{"col":"math","row":"Alice","val":90},{"col":"sci","row":"Alice","val":85},{"col":"math","row":"Bob","val":78}]Output:
{"Bob":{"math":78},"Alice":{"sci":85,"math":90}}Example 2
Input:
records = [{"col":"c1","row":"r1","val":1}]Output:
{"r1":{"c1":1}}Worked solution and explanation
What this really is
This is a sparse two-level dict build wearing a spreadsheet costume. The skill being probed: can you grow a nested dict whose inner dict may not exist yet, without clobbering rows that share an outer key? Everyone writes the loop. The tell is whether you create result[row] exactly once and keep adding columns to it as more records for that same row arrive. Get that wrong and Alice's sci entry wipes out her math entry.
Break down the requirements
Step 1: The row label is the outer key
Each record's row field is the outer key. Different records can share the same row, so you cannot treat each record as a fresh row.
Step 2: Columns map to values inside each row
Within a row, set result[row][col] = val. Because rows are sparse, you only ever write the columns that show up; there is no dense matrix to fill.
Step 3: Initialize the inner dict once
Create the inner dict the first time a row is seen, and never again. This is the one line that separates a correct answer from one that silently drops columns.
The solution
def pivot_table(records):
result = {}
for record in records:
row = record['row']
col = record['col']
val = record['val']
if row not in result:
result[row] = {}
result[row][col] = val
return resultOne pass, inner dict created only on first sight of a row.
Common follow-up questions
- What if you need the reverse operation, turning the nested dict back into long-format records? (Tests iterating the nested dict and producing flat records with row/col/val keys.)
- What if duplicate row/col pairs should be summed instead of overwritten? (Tests defining a conflict policy: last-write-wins, sum, or raise.)
- How would you turn this into a pandas DataFrame, and where do sparse rows bite you? (Tests pd.DataFrame.from_dict(result, orient='index') and the pivot vs `pivot_table` distinction.)