Skip to main content
All questions
MediumStrings · Recursion

Flatten Dictionary

Written by a community member · · 4 attempts · 25% pass

1

Given a nested dictionary, write a function flattenDictionary that returns a flattened version of it.

The dictionary is given as its list of root-to-leaf paths. Each path is a list of keys, outermost first, followed by the leaf value as a string: {'Key2': {'a': '2'}} is [['Key2', 'a', '2']].

When flattening, concatenate the keys along each path using a period (.) separator. If a key is empty, exclude it from the output key path. Empty keys may appear at any nesting level.

Return one [flattened_key, value] pair per path, in the order the paths are given.

Examples:

  1. Input: [['Key1', '1'], ['Key2', 'a', '2'], ['Key2', 'b', '3']] (the dictionary {'Key1': '1', 'Key2': {'a': '2', 'b': '3'}})
    Output: [['Key1', '1'], ['Key2.a', '2'], ['Key2.b', '3']]

  2. Input: [['', 'a', '1'], ['b', '2']] (the dictionary {'': {'a': '1'}, 'b': 2})
    Output: [['a', '1'], ['b', '2']]

Constraints:

  • Keys and values are strings.
  • Every path has at least one key and one value.