Turn dotted keys into a nested dictionary
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Netflix's technical phone screen, last asked Aug 2025. It tests dictionaries, recursion and parsing.
A model checkpoint lists its parameters under flat dotted names such as layer1.attention.q_proj.weight, layer1.attention.k_proj.weight and layer1.mlp.fc1.weight. Write a Python function that turns this flat mapping into a nested dictionary grouped by layer number, so parameters of the same component (attention, mlp, …) sit together under their layer.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
nest_params(params: dict[str, Any]) -> dictmaps each namelayer{n}.<path>toresult[n][<path segments>...] = value, withnas an integer. Names that do not start withlayer{n}.go unchanged underresult["other"]. - A name that would be both a leaf and a prefix of another name (for example
layer1.mlpandlayer1.mlp.fc1.weight) raises aValueError.
Example
nest_params({
"layer1.attention.q_proj.weight": (64, 64),
"layer1.attention.k_proj.weight": (64, 64),
"layer1.mlp.fc1.weight": (256, 64),
"layer2.attention.q_proj.weight": (64, 64),
"embed.weight": (1000, 64),
})
->
{
1: {"attention": {"q_proj": {"weight": (64, 64)}, "k_proj": {"weight": (64, 64)}},
"mlp": {"fc1": {"weight": (256, 64)}}},
2: {"attention": {"q_proj": {"weight": (64, 64)}}},
"other": {"embed.weight": (1000, 64)},
}
Constraints
- Up to 10^5 names, each with up to about 10 segments.
- Total work linear in the total length of the names.
Clarifying questions
- What is the grouping rule: by layer number only, or by full path?
- How should names that do not follow the
layer{n}pattern be handled? - What happens on duplicate names or leaf/prefix conflicts?
- Should layer numbers be integers or strings, and should output be sorted?
What a strong answer covers
- A clear, stated grouping rule and parsing of the layer prefix with validation (
layer12versuslayersversuslayer1a). - Building the nested structure with
setdefaultor a recursive helper, detecting conflicts when a leaf meets a dict and vice versa. - Handling of nonconforming keys and duplicates, with tests for each.
-
O(total characters)time and space.
Follow-ups
- Write the reverse conversion from the nested dict back to flat names, and test that the round trip is exact.
- Group by component across layers instead (all
attention.q_proj.weighttensors together). - Treat numeric segments in the middle (
blocks.3.attn) as list indices.
Where it's asked
- Netflix · Technical phone screen · Last asked Aug 202560 min · Coding, practical problem solving, or SQL and pipeline design, depending on the org
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
