#K59992. Flattening a Nested Dictionary
Flattening a Nested Dictionary
Flattening a Nested Dictionary
You are given a nested dictionary. Your task is to flatten the dictionary by concatenating the keys of the nested dictionaries into a single key, with levels separated by a given delimiter.
For example, if the input dictionary is {"a": 1, "b": {"c": 2, "d": {"e": 3}}}
and the delimiter is ., the flattened dictionary should be {"a": 1, "b.c": 2, "b.d.e": 3}
. In mathematical form, if you have keys \(k_1, k_2, \dots, k_n\) then the new key is given by
$$ concatenated\_key = k_1 \; delimiter \; k_2 \; delimiter \; \dots \; delimiter \; k_n$$
Write a program that reads a JSON string representing the dictionary from standard input and a delimiter on the next line, and outputs the flattened dictionary as a JSON string. If the delimiter line is empty, use .
as the default delimiter.
inputFormat
The input is given via stdin as follows:
- The first line is a JSON string representing a nested dictionary. Keys are strings and values will be either integers or another dictionary.
- The second line is a string representing the delimiter. If this line is empty, use
.
as the default delimiter.
outputFormat
Output the flattened dictionary as a JSON string to stdout.
## sample{"a":1,"b":2}
.
{"a":1,"b":2}