python - merge all keys of dictionary of dictionary and create new dictionary -


i having 1 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 solve

 >>> def handle(inp):     out = {}     in inp:         if type(inp[i]) dict:             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 not able solve .

you need recursively each dictionary.

this works.

>>> >>> def handle(inp): ...     out = {} ...     in inp: ...         if type(inp[i]) dict: ...             inp[i]=handle(inp[i]) ...             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'} >>> 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -