#C9608. Flatten Nested Dictionary
Flatten Nested Dictionary
Flatten Nested Dictionary
Given a nested dictionary d
and a string delimiter
, your task is to create a flattened version of the dictionary. In the flattened dictionary, each key is formed by concatenating the keys from the original nested structure, separated by the given delimiter
.
For example, given the nested dictionary
{'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': 4}}}
and delimiter = "_"
, the flattened dictionary is
{'a': 1, 'b_c': 2, 'b_d_e': 3, 'b_d_f': 4}
The task can be described mathematically as: \[ \text{flatten}(d, s) = \{\;k\_1 \oplus s \oplus k\_2 \oplus s \oplus \cdots \oplus k\_n : v\}\quad\text{for each nested key path}\; (k_1, k_2, \dots, k_n) \text{ with value } v. \]
Note that if a value is not a dictionary, it remains unchanged.
inputFormat
The input is read from stdin
and consists of two lines:
- A JSON-formatted string representing the nested dictionary.
- A string representing the delimiter.
Both lines are guaranteed to be non-empty.
outputFormat
The output should be printed to stdout
as a JSON-formatted string of the flattened dictionary.
{"a": 1, "b": {"c": 2, "d": {"e": 3, "f": 4}}}
_
{"a":1,"b_c":2,"b_d_e":3,"b_d_f":4}