loading...
Cover image for 6-10PM challenge problem #005

6-10PM challenge problem #005

akbhairwal profile image akbhairwal Updated on ・1 min read

6-10PM challenge (6 Part Series)

1) 6-10PM challenge problem #001 2) 6-10PM challenge problem #002 3 ... 4 3) 6-10PM challenge problem #003 4) 6-10PM challenge problem #004 5) 6-10PM challenge problem #005 6) 6-10PM challenge problem #006

Flatten a Dictionary

A dictionary is a collection of unique keys and their values. The values can typically be of any data type (i.e an integer, boolean, double, string etc) or other dictionaries (dictionaries can be nested). However, for this exercise assume that values are either an integer, a string or another dictionary.

Given a dictionary dict, write a method flattenDictionary that returns a flattened version of it .

If you’re using a compiled language such Java, C++, C#, Swift and Go, you may want to use a Map/Dictionary/Hash Table that maps strings (keys) to a generic type (e.g. Object in Java, AnyObject in Swift etc.) to allow nested dictionaries.

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 concatenating Key2, c and d the result key would be Key2.c.d.

Solution

6-10PM challenge (6 Part Series)

1) 6-10PM challenge problem #001 2) 6-10PM challenge problem #002 3 ... 4 3) 6-10PM challenge problem #003 4) 6-10PM challenge problem #004 5) 6-10PM challenge problem #005 6) 6-10PM challenge problem #006

Posted on by:

Discussion

markdown guide
 

A js solution:

function flatten(i) {
    const res = {};
    for(let key of Object.keys(i)) {
        if (typeof i[key] == 'object') {
            const temp = flatten(i[key]);
            for (let tempKey of Object.keys(temp)) {
                const sep = key !== '' ? '.' : '';
                res[key+sep+tempKey] = temp[tempKey]

            }
        } else {
            res[key] = i[key]
        }
    }
    return res;
}
 

Here is a Python solution,


def flat_dict(d : dict) -> dict:
    temp_dict = {}
    for k1, v1 in d.items():
        if isinstance(v1, dict):
            for k2, v2 in flat_dict(v1).items():
                temp_dict[k1 + ("." if k2 and k1 else "")+ k2] = v2
        else:
            temp_dict[k1] = v1
    return temp_dict

Test cases,

d1 = {
        "Key1" : "1",
        "Key2" : {
            "a" : "2",
            "b" : "3",
            "c" : {
                "d" : "3",
                "e" : {
                    "" : "1"
                }
            }
        }
    }

print(flat_dict(d1))
# output -> {'Key1': '1', 'Key2.a': '2', 'Key2.b': '3', 'Key2.c.d': '3', 'Key2.c.e': '1'}

d2 = {
        "Key1" : "1",
        "Key2" : {
            "a" : "2",
            "b" : "3",
            "" : {     # no key here
                "d" : "3",
                "e" : {
                    "" : "1"
                }
            }
        }
    }

print(flat_dict(d2))
# output -> {'Key1': '1', 'Key2.a': '2', 'Key2.b': '3', 'Key2.d': '3', 'Key2.e': '1'}
 

Thank you Vidit. Your solution works.