Pivot long-format records

Write codeMedium30 minSnowflake and Databricks style

Your task

Pivot a list of long-format records into a wide table. Each record is a dict with an index_key, a col_key, and a numeric val_key. Produce a 2D table whose first row is a header ['_', col1, col2, ...] with the distinct column-key values sorted ascending, followed by one row per distinct index value (sorted ascending): [index_value, v_col1, v_col2, ...], using 0 where a given (index, column) pair has no record. Return the table as a list of lists.

Examples

pivot(rows: list[dict], index_key: str, col_key: str, val_key: str) -> list[list]
Example 1
Inputpivot([{"d": "mon", "p": "x", "n": 1}, {"d": "mon", "p": "y", "n": 2}, {"d": "tue", "p": "x", "n": 3}], "d", "p", "n")
Output[["_", "x", "y"], ["mon", 1, 2], ["tue", 3, 0]]