Skip to main content
All Questions

Flatten a Dictionary

Medium
Unlock detailed company stats for this questionUpgrade

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.