766. Flatten and unflatten nested config dictionaries
Experiment trackers and config systems often store nested settings as flat keys like 'optimizer.lr'. You need to convert both ways.
Write transform(obj, mode, sep='.'). In mode 'flatten', obj is a nested dict whose values are dicts or leaf values. Return a flat dict whose keys join the path with sep. An empty nested dict is a leaf and is kept as the value {}.
In mode 'unflatten', obj is a flat dict. Split each key on sep and rebuild the nested dict. If two keys conflict, because one key is a leaf and also a prefix of another (for example 'a' and 'a.b'), return the string 'conflict'.
def transform(obj, mode, sep='.')Example 1
Input: transform({'model': {'layers': 12, 'dim': 768}, 'seed': 0}, 'flatten')
Output: {'model.layers': 12, 'model.dim': 768, 'seed': 0}
Example 2
Input: transform({'a.b': 1, 'a.c': 2}, 'unflatten')
Output: {'a': {'b': 1, 'c': 2}}
Constraints
- Keys never contain sep themselves.
- Up to 10,000 leaves.
Hint 1
Recursion with a prefix string handles flatten.
Hint 2
For unflatten, walk parts[:-1] creating dicts, then set the last part.
Hint 3
Think about which side of a collision arrives first.
Common mistakes
- Recursing into empty dicts and losing them.
- Detecting only one order of the leaf and prefix conflict.
- Treating a leaf value that is itself {} as a branch.
Understand the idea
Path encoding: a nested dict and a flat dict with joined keys hold the same information, as long as leaves and branches can be told apart.