progress

~/problems / Streams & durability / Serialization and durability

Escaped key=value settings file

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 label printer stores settings as text, one key=value per line, which breaks when a value has a newline or a key has =. Length prefixes are one fix; here you use escaping, so the file stays readable.

Implement dumps(settings: dict[str, str]) -> str and loads(text: str) -> dict[str, str] with loads(dumps(d)) == d, keeping order:

  • One line per entry: escape(key) + "=" + escape(value) + "\n" (the last line too). An empty dict gives "".
  • escape turns \ into \\, = into \=, and a newline into \n (backslash, letter n). Every other character, including \r and tabs, is written as is.
dumps({"size": "small", "a=b": "line1\nline2", "dir": "C:\\labels"})
# 'size=small\na\\=b=line1\\nline2\ndir=C:\\\\labels\n'
# as the file shows it:
#   size=small
#   a\=b=line1\nline2
#   dir=C:\\labels

loads("x=\n=y\n")   # {"x": "", "": "y"}
loads("")           # {}

loads raises ValueError for non-empty text without a final newline, a line without exactly one unescaped =, a \ not followed by \, = or n, or a repeated key.

Show hint

split on '\n' only (text.split('\n'), not splitlines(), which also breaks at \r and others), then scan each line: on \, emit what the next character stands for; an unescaped = switches from key to value.

Topic: Serialization and durability. Length-prefixed encodings, write-ahead logs, checkpoints and recovery.

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