PY-52
Flatten and Rebuild Nested Records
Task
Define this plain record, then write flatten_records(records, encode_value)
and rebuild_records(rows, decode_value):
Each record ID is unique. data is built from dictionaries, lists, and scalar
values. Dictionary keys are strings. encode_value(value) converts one scalar
to text; decode_value(text) reverses that conversion.
The flat form contains one tuple for every node:
(record_id, path, kind, value)
path is a tuple of steps from the record's data root. A dictionary step is
("key", key) and a list step is ("index", index). kind is "dict",
"list", or "value". Container rows use None for value; scalar rows use
encode_value. Emit each root first, then visit dictionary values in insertion
order and list values from left to right.
rebuild_records receives rows in that order and returns the original record
shape. The supplied rows are valid, contain one root per record, and never
refer to a missing parent. Preserve record order and do not modify an input.
Example
records = [NestedRecord("r1", {"scores": [4, 7], "note": "ok"})]
The first three flat rows describe the root dictionary, the scores list, and
its first value:
Empty dictionaries and lists still receive their own row, so rebuilding does not lose them.
Your implementation
Edit solution.py, keep the record definition above, and keep these function
signatures:
Do not import a serialization library, modify an input, print, or ask for input. The helper functions own scalar serialization; your code owns paths, container shape, record identity, and order.