# Pivot Records

> Long format is easy. Wide format is useful.

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

Domain: Python · Difficulty: hard · Seniority: L4

## Problem

Given a list of dicts (each with 'row', 'col', 'val'), return a nested dict {row: {col: val}}.

## Worked solution and explanation

### Why this problem exists in real interviews

Pivoting flat records into a nested lookup structure tests **nested dict construction** and is the Python equivalent of a SQL PIVOT. It checks whether you handle the two-level key hierarchy correctly.

---

### Break down the requirements

#### Step 1: Group by row key

For each record, the 'row' field is the outer key.

#### Step 2: Map column keys to values within each row

For each record, set `result[row][col] = val`.

#### Step 3: Handle first-seen rows

Initialize an empty inner dict when a row key is seen for the first time.

---

### The solution

**Two-level dict construction from flat records**

```python
def pivot(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 result
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the number of records. Each record is processed once.
> 
> **Space:** O(n) for the nested dict, one entry per record.

> **Interviewers Watch For**
>
> Clean two-level dict initialization. Using `setdefault(row, {})` is also good; the manual check is more explicit.

> **Common Pitfall**
>
> Assuming rows and columns form a complete matrix. In practice, some row-column combinations may be missing, resulting in sparse inner dicts.

---

## Common follow-up questions

- What if you need the reverse operation (unpivot)? _(Tests iterating the nested dict and producing flat records with row/col/val keys.)_
- What if duplicate row-col pairs exist? _(Tests defining a conflict resolution: last-write-wins, sum, or raise an error.)_
- How would you convert this to a pandas DataFrame? _(Tests `pd.DataFrame.from_dict(result, orient='index')` and understanding pivot vs. pivot_table.)_

## Related

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