easy +10 pts

Parse table rows

Parse a simple markdown-style table into a list of row dictionaries.

You are given a string containing a simple table. The table uses a pipe character (`|`) to separate columns, and each row is on its own line. The first non-empty line is the header row, which defines the column names. Immediately after the header, there may be a separator line that consists of pipes, dashes, and spaces (e.g., `| --- | --- |`), which should be ignored. All remaining non-empty lines are data rows. Write a function `parse_table_rows(table: str) -> list[dict]` that returns a list of dictionaries, one for each data row, with keys taken from the header row and values taken from the data row. Each column value should be stripped of surrounding whitespace. If a row has fewer cells than the header, missing values should be an empty string. If a row has more cells than the header, the extra cells should be ignored. For example, given the table: ``` | Name | Age | City | |------|-----|------| | Alice | 30 | Paris | | Bob | 25 | Lyon | ``` The function should return: ```python [ {'Name': 'Alice', 'Age': '30', 'City': 'Paris'}, {'Name': 'Bob', 'Age': '25', 'City': 'Lyon'} ] ``` The separator line (the one containing dashes) is always present in the input, but you should not assume the exact number of dashes. Header and data rows are guaranteed to have at least one column. Lines are separated by `\n`. The input may have leading/trailing blank lines, which should be ignored.

Constraints

- Input string length is at most 10,000 characters. - At least one header and one data row. - Column names and values may contain any characters except `|` and newlines. - Do not use external libraries.

Example

>>> table = "| Name | Age | City |\n|------|-----|------|\n| Alice | 30 | Paris |\n| Bob | 25 | Lyon |"
>>> parse_table_rows(table)
[{'Name': 'Alice', 'Age': '30', 'City': 'Paris'}, {'Name': 'Bob', 'Age': '25', 'City': 'Lyon'}]

>>> table2 = "| A | B |\n|---|--|\n| 1 | 2 |\n| 3 |\n"
>>> parse_table_rows(table2)
[{'A': '1', 'B': '2'}, {'A': '3', 'B': ''}]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Split the input into lines and filter out empty lines first.
Identify the header line and skip the separator line (one that contains only dashes, pipes, and spaces).
Parse each remaining line by splitting on '|' and stripping whitespace, then pad with empty strings to the header length.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.