The Log Decoder

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L4

Problem

You're ingesting raw application logs where each line in lines is a run of space-separated key=value tokens. Turn each line into a dict mapping its keys to their string values, one dict per line in the same order, and leave every value as a string even when it contains an =.

Every line holds a secret.

Example 1

Input:

lines = ["ts=1234 level=ERROR msg=timeout","ts=1235 level=INFO msg=ok"]

Output:

[{"ts":"1234","level":"ERROR","msg":"timeout"},{"ts":"1235","level":"INFO","msg":"ok"}]

Example 2

Input:

lines = ["path=/api?x=1 code=200"]

Output:

[{"path":"/api?x=1","code":"200"}]

Worked solution and explanation

What this really is

This is string tokenizing dressed up as log ingestion. The real skill: turning each space-separated key=value token into a dict entry while keeping values that themselves contain an = intact. Anyone can call split. The trap is token.split('=') with no limit: the moment a value looks like url=http://x?a=1, it shatters into three pieces and the unpack either crashes or silently drops the query string. The fix is a bounded split, split('=', 1), applied per token.


Break down the requirements

Step 1: Split each line into tokens

Splitting on whitespace with a bare line.split() also collapses runs of extra spaces, so stray double spaces never leave you with empty tokens. A blank line yields no tokens and therefore an empty dict, which keeps its position in the output.

Step 2: Split each token once on the equals sign

The part before the first = is the key, everything after is the value. The maxsplit of 1 is what keeps a value like http://x?a=1 whole instead of breaking on its inner =, and it turns msg= into an empty-string value rather than an error.

Step 3: Build one dict per line

Collect the key-value pairs from one line into a dict, then append it to the result list so output order mirrors input order. Plain assignment means a key that repeats in a line keeps its last value.


The solution

Two-level split: whitespace then a single equals
def parse_log_lines(lines):
    result = []
    for line in lines:
        entry = {}
        for token in line.split():
            key, value = token.split('=', 1)
            entry[key] = value
        result.append(entry)
    return result

Common follow-up questions