A plant nursery prints pot labels from one-line specs like
name="Boston fern" water=weekly light="bright, indirect"
Write parse_tags(line: str) -> dict[str, str], raising ValueError if the line is malformed.
Grammar (the only whitespace is " "):
- Zero or more pairs, separated by one or more spaces; leading and trailing spaces are fine.
- A pair is
key=value, no spaces around=. A key is one or more ofA-Z a-z 0-9 _, and appears at most once per line. - A value is bare (one or more characters, none a space,
"or=; backslash is ordinary) or quoted:"..."where\"means",\\means\, any other escape is an error, and""is empty. - A value is followed by a space or the end (
a="x"b=1is malformed).
Anything else raises ValueError.
parse_tags('name="Boston fern" water=weekly')
# {"name": "Boston fern", "water": "weekly"}
parse_tags(r'note="say \"hi\"" path=C:\pots')
# {"note": 'say "hi"', "path": "C:\\pots"}
parse_tags(" ") # {}
parse_tags("a=1 a=2") # ValueError: duplicate key 'a'
parse_tags('a="open') # ValueError: unterminated quote
parse_tags("a= 1") # ValueError: empty value
Show hint
walk an index: skip spaces, read a key, expect =, then read a quoted value (handling \) or a bare one up to a space. Raise as soon as something doesn't match.