Data science: Pivot a long table

People read wide tables more easily. Pivot a long table into one row per subject.

What to build

A program that pivots long data into a wide table.

Requirements

  • Print a header: the row label given, then the column names in alphabetical order, separated by commas.
  • Then one line per row key, in the order the keys first appear, with the values in the header's column order and - where there is none. If a row and column pair appears more than once, the last value wins.

Input

Line 1: the label for the row keys. Line 2: n. Then n lines ROW,COLUMN,VALUE.

Output

The header, then one line per row key.

Constraints

1 ≤ n ≤ 1000; no commas inside values.

Example

Input:

student
4
Asha,math,80
Ben,math,65
Asha,physics,75
Ben,chem,70

Output:

student,chem,math,physics
Asha,-,80,75
Ben,70,65,-

Why it works

A dictionary of dictionaries holds exactly one value per row and column pair, which is what a pivot needs, and the sorted set of columns gives every row the same layout with gaps shown explicitly.

Examples

Example 1 · Input
student
4
Asha,math,80
Ben,math,65
Asha,physics,75
Ben,chem,70
Expected output
student,chem,math,physics
Asha,-,80,75
Ben,70,65,-
Example 2 · Input
city
2
Dhaka,2024,10.4
Dhaka,2023,10.2
Expected output
city,2023,2024
Dhaka,10.2,10.4

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Keep a dictionary from row key to a dictionary of column → value; a later value for the same pair replaces the earlier one.

Hint 2

Collect the column names in a set and sort them for the header.

Solution

Show one correct solution (try it yourself first)
label = input()
n = int(input())
table = {}
columns = set()
for _ in range(n):
    row, column, value = input().split(",")
    table.setdefault(row, {})[column] = value
    columns.add(column)
order = sorted(columns)
print(",".join([label] + order))
for row, values in table.items():
    print(",".join([row] + [values.get(c, "-") for c in order]))

Lesson: Tidy data: reshaping tables →