easy +8 pts

Parse key=value pairs

Convert a string of key=value pairs into a dictionary, handling spaces and quoted values.

Write a function `parse_key_value_pairs(text)` that takes a string containing zero or more space-separated `key=value` pairs and returns a dictionary mapping keys to values as strings. Rules: - Pairs are separated by one or more spaces. - Each pair consists of a key and a value separated by the first `=`. - Keys and values contain no spaces (values may be quoted to include spaces). - If a value is surrounded by double quotes (`"`), the quotes are removed and the value may contain spaces. A quoted value is always the last token in its pair; i.e., no additional `key=value` follows it within the same pair. An empty quoted value is valid and becomes an empty string. - Keys are not quoted. Keys may contain alphanumeric characters and underscores. If a key appears multiple times, the last occurrence wins. - If text is empty or contains no valid `key=value` pairs, return an empty dictionary. - You do not need to handle escaped quotes or nested quotes. Implement the function exactly as described. The returned dictionary should have string keys and string values.

Constraints

Input string length: 0 — 1000 characters. The input will always be a string. You may assume the input does not contain unquoted spaces inside values.

Example

>>> parse_key_value_pairs("name=Alice age=30")
{'name': 'Alice', 'age': '30'}

>>> parse_key_value_pairs("greeting=\"Hello world\" lang=en")
{'greeting': 'Hello world', 'lang': 'en'}

>>> parse_key_value_pairs("")
{}

>>> parse_key_value_pairs("color=\"blue sky\"")
{'color': 'blue sky'}

>>> parse_key_value_pairs("empty=\"\" key=value")
{'empty': '', 'key': 'value'}
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Split the text by spaces first, but remember that quoted values can contain spaces.
When you see a token containing `=` and the value part starts with a double quote, you may need to merge subsequent tokens until the closing quote.
Handle the case where a key might be repeated — later pairs should overwrite earlier ones.
When a quoted value is just the opening and closing quote (like `""`), the value should become an empty string.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.