Parse a Device Record

Asked at NetflixPhone screen

Reported by the problem's creator, not verified

A device log record is a single line of text:

machine_code, timestamp, field1, field2, $[free-form]&

It has four comma-separated fixed fields, then a free-form section that starts with $[ and ends with ]&. Spaces around every piece are ignored.

Implement parse_record(line, machines, keys). It returns a dictionary with the keys "machine", "timestamp", "fields", "attrs", in this order:

  • "machine": machines[machine_code], or "UNKNOWN" when the code is not in machines.
  • "timestamp": the timestamp as an integer.
  • "fields": the list [field1, field2] as trimmed strings.
  • "attrs": the free-form pairs.

Free-form pairs are written key: value, separated by commas. Only the first colon in a pair separates the key from the value, so a value can contain colons. A key found in keys is renamed to keys[key]; other keys keep their own name. Empty items between commas are skipped, and $[]& gives an empty attrs.

Examples

  1. Example 1

    Input: {"keys":{"t":"title","v1":"video","v2":"audio"},"line":"123, 1231231231, AAA, BBB, $[v1: SSS, v2: TTT]&","machines":{"7":"PACKAGER","42":"ORIGIN","123":"ENCODER"}}

    Output: {"attrs":{"audio":"TTT","video":"SSS"},"fields":["AAA","BBB"],"machine":"ENCODER","timestamp":1231231231}

    Explanation: The code 123 maps to ENCODER, the timestamp becomes the integer 1231231231, and v1 and v2 are renamed to video and audio.

Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question

Code

Loading editor…

Ln 1, Col 1

Start an attempt to use Coach.