#K48852. Flatten a Nested Dictionary
Flatten a Nested Dictionary
Flatten a Nested Dictionary
You are given a JSON object (dictionary) that may include nested dictionaries. Your task is to flatten it by merging keys from nested dictionaries into a single key at the top level. The keys in the flattened dictionary are formed by concatenating all the keys from the root to the leaf using a dot (.
) as a separator.
More formally, for a nested dictionary d
, the flattened dictionary f
should satisfy
[ f(\texttt{key}_1.\texttt{key}_2...\texttt{key}_n) = d[\texttt{key}_1][\texttt{key}_2]...[\texttt{key}_n] ]
Your program should read the input from stdin
(which is a JSON object) and write the flattened dictionary to stdout
in JSON format. Note that if a dictionary is empty, the flattened dictionary is also empty. The keys in the input may represent numbers as well as strings; however, in the flattened result, every key is a string.
inputFormat
The input is given via standard input as a single JSON object representing a dictionary. The keys are strings (or string representations of numbers) and the values can be integers or nested JSON objects.
outputFormat
Output the flattened dictionary as a JSON object to standard output. The flattened keys should be joined by a dot (.
). There should be no extra spaces in the output.
{"a":1,"b":{"c":2,"d":{"e":3}},"f":{"g":4}}
{"a":1,"b.c":2,"b.d.e":3,"f.g":4}