#C14067. Flatten Nested Dictionary

    ID: 43675 Type: Default 1000ms 256MiB

Flatten Nested Dictionary

Flatten Nested Dictionary

You are given a nested dictionary and your task is to flatten it. In the flattened dictionary, the key for each element is generated by concatenating the keys along the path from the root to that element using a specified separator. By default, the separator is _. However, a custom separator may be provided as input. Formally, if you denote the flattening operation as \(F(d, s)\) for a dictionary \(d\) and separator \(s\), then for any key \(k\) whose value is a nested dictionary \(d'\), each key in \(F(d', s)\) will be concatenated as parent key \(s\) child key. Otherwise, the key remains unchanged.

Example: For \(d = {"a": {"b": 1, "c": 2}, "d": 3}\), the flattened dictionary is {"a_b": 1, "a_c": 2, "d": 3}.

inputFormat

The input is read from standard input (stdin) and consists of one or two lines:

  • The first line is a JSON-formatted string that represents a nested dictionary. Each key is a string, and each value is either an integer or another dictionary.
  • The second line is optional. If provided, it is a string representing the separator to be used; otherwise, the default separator _ is used.

outputFormat

The output should be printed to standard output (stdout) as a JSON-formatted string representing the flattened dictionary.

## sample
{"a": {"b": 1, "c": 2}, "d": 3}
{"a_b":1,"a_c":2,"d":3}