Cross-Tabulate Records by Composite Row and Column Keys
Arrays & HashingAuto-graded · 18 test casesLast updated
Group records by composite row and column keys, sum a value field per pair, and return the axes in first-seen order with a dense grid that has zeros for missing pairs.
You are given a list of records, where each record is a dictionary mapping column names to values. Build a cross-tabulation (a pivot table) that sums one numeric column over groups defined by two sets of key columns.
Task
Implement a function that takes:
rows: a list of dictionaries, each mapping a column name (string) to a value (string or number).row_key_columns: a list of column names. Together, their values in a record form that record's row key.col_key_columns: a list of column names. Together, their values in a record form that record's column key.value_column: the name of the numeric column to add up.
Return a dictionary with exactly three entries:
"row_keys": the distinct row keys, each written as a list of values in the same order asrow_key_columns."col_keys": the distinct column keys, each written as a list of values in the same order ascol_key_columns."values": a 2D list with one inner list per row key and one entry per column key. Entryvalues[i][j]is the sum ofvalue_columnover all records whose row key isrow_keys[i]and whose column key iscol_keys[j].
Rules
- Ordering: Row keys and column keys appear in the order in which they are first encountered while scanning
rowsfrom start to finish. Do not sort them. - Missing pairs: If no record has a particular (row key, column key) pair, the corresponding cell is
0. - Distinctness: Two keys are the same only if all their components are equal. Keys with different components in different positions are different keys.
- Empty input: If
rowsis empty, return{"row_keys": [], "col_keys": [], "values": []}. - Every record contains all the columns that are referenced.
- Key values are kept as they appear in the input (for example, the integer
2023stays an integer).
Constraints
0 <= len(rows) <= 50,000row_key_columnsandcol_key_columnseach contain at least one column name, and the value column is not listed in either.- Value-column entries are integers or floats.
- The number of distinct row keys times distinct column keys is small enough to hold the dense grid in memory.
- Aim for roughly linear time in the number of records, plus the size of the output grid.
Examples
Example 1
Input: build_cross_tab([{'city': 'SF', 'product': 'Book', 'sales': 10}, {'city': 'SF', 'product': 'Pen', 'sales': 4}, {'city': 'NY', 'product': 'Book', 'sales': 7}, {'city': 'SF', 'product': 'Book', 'sales': 3}], ['city'], ['product'], 'sales')
Output: {'row_keys': [['SF'], ['NY']], 'col_keys': [['Book'], ['Pen']], 'values': [[13, 4], [7, 0]]}
Example 2
Input: build_cross_tab([{'region': 'West', 'quarter': 1, 'product': 'A', 'amount': 5}, {'region': 'West', 'quarter': 1, 'product': 'B', 'amount': 8}, {'region': 'West', 'quarter': 2, 'product': 'A', 'amount': 6}, {'region': 'East', 'quarter': 1, 'product': 'A', 'amount': 4}], ['region', 'quarter'], ['product'], 'amount')
Output: {'row_keys': [['West', 1], ['West', 2], ['East', 1]], 'col_keys': [['A'], ['B']], 'values': [[5, 8], [6, 0], [4, 0]]}
Example 3
Input: build_cross_tab([{'department': 'Eng', 'year': 2023, 'team': 'A', 'hours': 10}, {'department': 'Eng', 'year': 2023, 'team': 'A', 'hours': 2}, {'department': 'Sales', 'year': 2024, 'team': 'B', 'hours': 7}], ['department'], ['year', 'team'], 'hours')
Output: {'row_keys': [['Eng'], ['Sales']], 'col_keys': [[2023, 'A'], [2024, 'B']], 'values': [[12, 0], [0, 7]]}
Hints
Hint 1
Turn each record's key columns into a tuple. Tuples are hashable, so they can be used as dictionary keys, and a list of columns of any length is handled uniformly.
Hint 2
Record each distinct row key and column key the first time you see it, together with its position index. A dictionary from key to index gives you first-seen ordering and constant-time lookup.
Hint 3
Once you know how many distinct row keys and column keys there are, create a grid of zeros of that size, then add each record's value to the cell at its (row index, column index).
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every cell of the output is "the sum of the value column over all records that share a given row key and column key", so the whole task is a group-by-and-sum on a pair of composite keys.
- Build keys as tuples. For each record, make
row_key = tuple(record[c] for c in row_key_columns)and likewisecol_key. Tuples are hashable and compare element by element, so they work as dictionary keys no matter how many columns are used, and different component layouts never get confused with each other. - Assign indices in first-seen order. While scanning the records, store each new row key and column key in a list and in a dictionary that maps the key to its position. This gives the required ordering without sorting, and also avoids comparing mixed types such as ints and strings.
- Allocate a zero grid. Once the number of distinct row keys
Rand column keysCis known, create anR x Cgrid of zeros. Cells for pairs that never occur stay at 0, which is exactly the rule for missing combinations. - Accumulate. Scan the records again and add each value to
values[row_index[row_key]][col_index[col_key]]. - Format the output. Convert tuple keys back to lists and return the three entries.
Why it is correct
Each record has exactly one row key and one column key, so it is added to exactly one cell, the one that matches its pair. After the scan, each cell holds the sum over precisely the records that match its pair, and untouched cells remain 0. The index dictionaries are filled the first time a key appears, so the key lists follow first-seen order.
Complexity
Let N be the number of records, k the total number of key columns, R the number of distinct row keys and C the number of distinct column keys.
- Time:
O(N * k + R * C)expected, using hash lookups. TheR * Cterm is the cost of creating the dense grid. - Space:
O(R * C + (R + C) * k)for the output and the key lists.
Reference solution
from typing import Dict, List
def build_cross_tab(rows: List[Dict[str, object]], row_key_columns: List[str], col_key_columns: List[str], value_column: str) -> Dict[str, List]:
row_keys = []
col_keys = []
row_index = {}
col_index = {}
for row in rows:
row_key = tuple(row[column] for column in row_key_columns)
col_key = tuple(row[column] for column in col_key_columns)
if row_key not in row_index:
row_index[row_key] = len(row_keys)
row_keys.append(row_key)
if col_key not in col_index:
col_index[col_key] = len(col_keys)
col_keys.append(col_key)
values = [[0 for _ in col_keys] for _ in row_keys]
for row in rows:
row_key = tuple(row[column] for column in row_key_columns)
col_key = tuple(row[column] for column in col_key_columns)
values[row_index[row_key]][col_index[col_key]] += row[value_column]
return {
"row_keys": [list(key) for key in row_keys],
"col_keys": [list(key) for key in col_keys],
"values": values,
}