6/35
Part 1 of 7 · Dict of dictsLearn and do

The same insert nests any path of keys, such as dotted parameter names

A prep site lists turning flat parameter names into a nested dict grouped by layer as a Netflix machine learning engineer question (1 source). It's trie insertion, with the parts between the dots as the letters:

from pprint import pprint


def nest(flat):
    nested = {}
    for key, value in flat.items():
        *path, last = key.split(".")
        node = nested
        for part in path:
            node = node.setdefault(part, {})
        node[last] = value
    return nested


flat = {"layers.0.weight": 0.12, "layers.0.bias": 0.5,
        "layers.1.weight": -0.3, "head.weight": 1.7}
pprint(nest(flat), width=60, sort_dicts=False)
Predict

nest() runs on layers.0.weight, then on layers.0.bias. What happens at the second key?

Pick one to see what it prints.
Pick an answer above to see the rest