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.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Here is a Python solution,
Test cases,
Thank you Vidit. Your solution works.