#C14035. Flatten a Nested Dictionary
Flatten a Nested Dictionary
Flatten a Nested Dictionary
You are given a nested dictionary in JSON format. Your task is to flatten this dictionary so that the keys become the full path in the original dictionary, separated by a dot ('.'). For example, if you have a key "a"
whose value is a dictionary with key "b"
, that inner key should become "a.b"
in the flattened dictionary.
More formally, for a nested dictionary d, the flattening process produces a new dictionary f satisfying:
$$f(\text{parent_key} + \text{sep} + \text{child_key}) = d[\text{child_key}] $$if d[child_key]
is not a dictionary, and if it is a dictionary then the process is applied recursively.
The input is provided as a single line in JSON format representing the nested dictionary. The output should be the flattened dictionary in JSON format.
inputFormat
The input consists of a single line containing a JSON object representing a nested dictionary. The keys are strings and the values can be integers, strings, lists, or dictionaries. You can assume the input is well-formed.
Input Format: a single line JSON string from stdin
.
outputFormat
Output the flattened dictionary as a JSON object in a single line to stdout
. The keys in the flattened dictionary represent the full path to each non-dictionary value in the original nested dictionary, with keys concatenated together using a dot ('.') as the separator.
{"a": {"b": 1}}
{"a.b": 1}