Home > Back-end >  How to convert list of elements into dictionary of dictionaries
How to convert list of elements into dictionary of dictionaries

Time:10-09

How to turn this list -

list = ['your name', 'mother', 'age', '43']

into this dictionary of dictionaries -

dict = {'your name': 
        {'mother': 
            {'age': '43'}
        }
    }

CodePudding user response:

One option is to iterate backwards over the list, and continuously update the result dict D:

L = ['your name', 'mother', 'age', '43']

D = L[-1]  # '43'

for k in L[-2::-1]:
    D = {k: D}  # {'age': D}... {'mother': D}...

print(D)

Out:

{'your name': {'mother': {'age': '43'}}}
  • Related