Skip to main content

Flatten a Dictionary

MediumPremium

Given a dictionary dict, write a function flattenDictionary that returns a flattened version of it. Assume that values are either an integer, a string, or another dictionary.

If a certain key is empty, it should be excluded from the output (see e in the example below).

Example

input: dict = { "Key1" : "1", "Key2" : { "a" : "2", "b" : "3", "c" : { "d" : "3", "e" : { "" : "1" } } } } output: { "Key1" : "1", "Key2.a" : "2", "Key2.b" : "3", "Key2.c.d" : "3", "Key2.c.e" : "1" }

Important: when you concatenate keys, make sure to add the dot character between them. For instance, when concatenating Key2, c, and d the resulting key would be Key2.c.d.

Begin by analyzing the input. Can you identify a pattern?

Remember that a recursive approach can often work well when dealing with nested structures.

If you find yourself stuck while figuring out a recursive solution, consider how the keys of the dictionary can be built up with each recursive call.

How do you handle cases where the key is an empty string or null?