BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Data processing and features35 of 54 in topic

766. Flatten and unflatten nested config dictionaries

MediumData processing and features Pro

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'.

Functiondef 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.

Topics
Data processing and features
Similar questions
  • Split a dataset so every class keeps its shareMedium
  • Bin a feature into quantile buckets learned from training dataMedium
  • Frequency-encode a category with a shared bucket for rare and unseen valuesMedium
  • Generate K-fold train and validation index splitsMedium
All Data processing and features problems
Report
766 / 903
Python 3solution.pyPython idle
1
2
3
4
def transform(obj, mode, sep='.'):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS