The Column Shuffle

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

Domain
Python
Difficulty
medium
Seniority
L6
Asked in
JPMorgan Chase

Problem

A long-format metrics export gives you one record per reading, each carrying an id and a single amount, and the same id can recur across many records. For each id, spread its amounts across numbered keys amount_1, amount_2, and so on in the order they appear, and return one dict per id (its id plus those keys) with ids in first-appearance order.

Rows in, columns out. Number them.

Example 1

Input:

records = [{"id":"A","amount":10},{"id":"A","amount":20},{"id":"B","amount":5}]

Output:

[{"id":"A","amount_1":10,"amount_2":20},{"id":"B","amount_1":5}]

Example 2

Input:

records = [{"id":"X","amount":1},{"id":"X","amount":2},{"id":"X","amount":3}]

Output:

[{"id":"X","amount_1":1,"amount_2":2,"amount_3":3}]

Worked solution and explanation

What this really is

Strip the costume and this is a long-to-wide pivot done by hand: bucket each id's amounts, then turn a variable-length list into positional keys. Anyone can build the buckets. The part that separates people is realizing the column count is per id, not global: id 'A' might own three amount_* keys while 'B' owns one, so you cannot pre-declare a fixed header. Reach for a fixed set of columns and you either pad the short groups with junk or truncate the long ones.


Break it into two passes

Step 1: Bucket amounts by id

Walk the records once, appending each amount to a list keyed by id. A plain dict keeps ids in first-appearance order for free (Python 3.7+), which is exactly the output order you owe.

Step 2: Turn positions into numbered keys

For each id's list, the position IS the column: index 0 becomes amount_1, index 1 becomes amount_2. enumerate gives you the index and value together.

Step 3: Assemble the rows

Each output row is the id plus however many numbered keys that id earned. Rows come out in the order the dict iterates, which is first-appearance order.


The solution

Bucket, then pivot by position
def the_column_shuffle(records: list[dict]):
    groups = {}
    for rec in records:
        gid = rec['id']
        if gid not in groups:
            groups[gid] = []
        groups[gid].append(rec['amount'])
    result = []
    for gid, amounts in groups.items():
        row = {'id': gid}
        for i, amt in enumerate(amounts):
            row['amount_' + str(i + 1)] = amt
        result.append(row)
    return result

Common follow-up questions