Coding questions · Walmart Labs
Convert Dictionary to DataFrame
This question evaluates proficiency in Python data manipulation and pandas DataFrame construction, specifically handling nested list structures and aligning rows by identifiers.
Using Python and pandas, convert the following dictionary into a DataFrame. Each top-level key is a target column name, and each value is a list of [row_id, cell_value] pairs. Use the first element of each pair as the row identifier, align rows by row_id across all keys, and produce a wide DataFrame with one row per row_id and one column per top-level key.
Input:
data = {
'text1': [[123, '2'], [345, '3']],
'text2': [[123, '4'], [345, '4']]
}
Expected structure:
row_id = 123->text1 = '2',text2 = '4'row_id = 345->text1 = '3',text2 = '4'
Write Python code to create the DataFrame.
Convert Dictionary to DataFrame
Given a key-value style table kv_cells with columns (key_name, row_id, cell_value), pivot the data to produce one row per row_id and one column per key_name (text1, text2).
Table kv_cells
| column | type | constraints |
|---|---|---|
| key_name | VARCHAR | NOT NULL |
| row_id | INTEGER | NOT NULL |
| cell_value | VARCHAR | NOT NULL |
Sample data:
| cell_value | key_name | row_id |
|---|---|---|
| 2 | text1 | 123 |
| 3 | text1 | 345 |
| 4 | text2 | 123 |
| 4 | text2 | 345 |
Expected output
A wide result with one row per row_id and separate columns for text1 and text2, aligned by row_id. Cell values remain strings as in the source.
| row_id | text1 | text2 |
|---|---|---|
| 123 | 2 | 4 |
| 345 | 3 | 4 |
Hints
- Use conditional aggregation with CASE expressions to pivot key_name values into columns.
- GROUP BY row_id and compute each target column with MAX(CASE WHEN key_name = 'textX' THEN cell_value END).