cswork / libraryOpen practice workspace

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

columntypeconstraints
key_nameVARCHARNOT NULL
row_idINTEGERNOT NULL
cell_valueVARCHARNOT NULL

Sample data:

cell_valuekey_namerow_id
2text1123
3text1345
4text2123
4text2345

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_idtext1text2
12324
34534

Hints

  1. Use conditional aggregation with CASE expressions to pivot key_name values into columns.
  2. GROUP BY row_id and compute each target column with MAX(CASE WHEN key_name = 'textX' THEN cell_value END).