medium +20 pts

Parse key-value lines

Parse lines like 'key=value; key2=value2' into a dictionary, correctly handling quoted values and escaped characters.

Write a function `parse_key_value_lines(lines)` that takes a list of strings, each representing a line of key-value pairs separated by semicolons. Each pair is in the format `key=value`, where key is a non-empty string consisting of alphanumeric characters and underscores, and value is either a plain string (no semicolons or quotes) or a double-quoted string. Within double-quoted values, the following escape sequences are supported: `\"` for a literal double quote, `\\` for a literal backslash, `\n` for a newline, and `\t` for a tab. Leading and trailing whitespace around keys and values (outside quotes) should be ignored. The function should return a single dictionary merging all key-value pairs across all lines. If a key appears multiple times, the later value should overwrite the earlier one. Lines that do not contain any key-value pairs should be ignored. If a line is malformed (e.g., missing '='), ignore that line. You can assume the input is a list of strings and the output should be a dictionary with string keys and string values.

Constraints

- `0 <= len(lines) <= 100` - Each line length <= 1000 characters. - Keys match `[A-Za-z_][A-Za-z0-9_]*`. - Values can be empty (e.g., `key=`). - No nested quotes or semicolons inside unquoted values. - Input will not contain invalid escape sequences (only the four mentioned).

Example

>>> parse_key_value_lines(['name=Alice; age=30', 'city="New York"'])
{'name': 'Alice', 'age': '30', 'city': 'New York'}
>>> parse_key_value_lines(['greeting="Hello\nWorld"', 'path="C:\\temp"'])
{'greeting': 'Hello\nWorld', 'path': 'C:\\temp'}
>>> parse_key_value_lines(['a=1; b=; c="x;y"', 'b=2'])
{'a': '1', 'b': '2', 'c': 'x;y'}
>>> parse_key_value_lines([])
{}
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Process each line separately, then merge into the final dictionary.
Use a state variable to know whether you are inside double quotes.
When parsing a value, if it starts with a double quote, read until the closing quote (handling escapes), otherwise read until semicolon or end of line.
After extracting a pair, strip whitespace from the key and the unquoted value.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.