DEV Community

Discussion on: 6-10PM challenge problem #005

Collapse
 
vidit1999 profile image
Vidit Sarkar

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'}
Collapse
 
akbhairwal profile image
akbhairwal

Thank you Vidit. Your solution works.