Write a function that takes a nested object of arbitrary depth and returns a flat object where each key is a path representing the hierarchy of keys, separated by dots (.). In Python the object is a dict.
Each value in the flat object is the value from the nested object. If a value is another object, the function should recursively flatten it into a key path.
Function Signature
def flatten_object(obj: dict) -> dict:
Rules
-
Keys are non-empty strings.
-
Keys never contain a
.
, so two different paths can never produce the same flat key.
-
Integer values are copied unchanged, including
0
.
-
Return the flat keys in the order a depth-first, left-to-right walk of the input reaches them, as in the examples.
Constraints
-
1 <= depth(obj) <= 125
-
Every object, at any level, has between 1 and 125 keys.
-
Each value is either a nested object or an integer.
Examples
Input: obj = {"a": 1, "b": {"c": 2, "d": {"e": 3}}}
Output: {"a": 1, "b.c": 2, "b.d.e": 3}
a holds an integer, so it stays as it is. b is an object, so its keys get the prefix b., and d inside it adds one more level, which gives b.d.e.
Input: obj = {"x": {"y": {"z": 0}}, "p": 4}
Output: {"x.y.z": 0, "p": 4}
The only leaf under x sits three levels down, so its key is x.y.z. Its value is 0, and it still appears in the output.
Input: obj = {"a": {"b": 1, "c": {"d": 2}}, "e": {"f": 3}}
Output: {"a.b": 1, "a.c.d": 2, "e.f": 3}
The leaves under a are reached through a then b, and through a, c, d. The path from the root to the last leaf is just e then f, so its key is e.f.