progress

~/problems / Iterators & parsers / Parsers and interpreters

Parse a label printer's key=value line

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

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 of A-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=1 is 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.

Topic: Parsers and interpreters. Tokenize, recursive descent, S-expressions, evaluation and type inference.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc