Prashant Gaur
Prashant Gaur

Reputation: 9828

merge all keys of dictionary of dictionary and create new dictionary

i am having one dictionary

{
   "a": "b",
   "c": {
       "d": "e",
       "f": {
           "g": "h",
           "i": "j"
       }
   }
}

i want output like:

{
   "a": "b",
   "c.d": "e",
   "c.f.g": "h",
   "c.f.i": "j"
}

I tried to solve

>>> def handle(inp):
    out = {}
    for i in inp:
        if type(inp[i]) is dict:
            for jj in inp[i].keys():
                out[i+'.'+jj] = inp[i][jj]
        else:
            out[i] = inp[i]
    return out

>>> handle(inp)
{'a': 'b', 'c.f': {'i': 'j', 'g': 'h'}, 'c.d': 'e'}

but i am not able to solve it completely .

Upvotes: 0

Views: 88

Answers (1)

Alagappan Ramu
Alagappan Ramu

Reputation: 2358

You need to do it recursively for each dictionary.

This works.

>>>
>>> def handle(inp):
...     out = {}
...     for i in inp:
...         if type(inp[i]) is dict:
...             inp[i]=handle(inp[i])
...             for jj in inp[i].keys():
...                 out[i+'.'+jj] = inp[i][jj]
...         else:
...             out[i] = inp[i]
...     return out
...
>>> handle(inp)
{'a': 'b', 'c.f.i': 'j', 'c.d': 'e', 'c.f.g': 'h'}
>>>

Upvotes: 3

Related Questions