easy +10 pts

Config Parser Reader

Parse an INI-style text and return a dictionary of parsed values.

Write a function `parse_config(text: str) -> dict` that parses a simplified INI-style configuration string into a Python dictionary. **Format rules:** - Lines may contain leading/trailing whitespace, which should be ignored. - Empty lines and lines where the first non-whitespace character is `#` or `;` are comments and should be skipped. - Section headers are on a line starting with `[` and ending with `]` (ignoring surrounding whitespace). The section name is the text between the brackets. The dictionary will have the section name as a key, and its value is a dictionary of the key-value pairs that follow it. - Key-value lines are of the form `key = value` or `key: value`. The separator is the first `=` or `:` that appears (outside of the value). Both key and value are stripped of leading/trailing whitespace. - A key-value line that appears before any section header should be placed under an empty-string section key (`''`). - If a line is otherwise invalid (no separator, malformed section header), ignore it completely. - All keys and values are returned as strings. No type conversion. - Sections may have duplicate keys: the last occurrence wins. - If the same section appears again later, its keys are merged into the existing section dictionary (later keys override earlier keys). Return the resulting dictionary. The order of keys in the dictionary does not matter for the test (we compare as dictionaries).

Constraints

- Input text length at most 10,000 characters. - Lines are separated by `\n`. - The function should run in O(n) time or better, where n is the number of characters.

Example

>>> parse_config("""
... # comment
... key1 = value1
... [section1]
... a = 1
... b: two
... [section2]
... x = y
... """)
{'': {'key1': 'value1'}, 'section1': {'a': '1', 'b': 'two'}, 'section2': {'x': 'y'}}

>>> parse_config("[s]\n k = v \n")
{'s': {'k': 'v'}}

>>> parse_config("")
{}
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Iterate line by line, strip whitespace, and skip empty or comment lines.
Use a variable to track the current section name.
Detect the separator (first '=' or ':') and split once.
Initialize the section dictionary if it doesn't exist before assigning key.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.