user20084690
user20084690

Reputation:

How to convert list of elements into dictionary of dictionaries

How to turn this list -

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

into this dictionary of dictionaries -

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

Upvotes: 0

Views: 56

Answers (2)

Rahul Hindocha
Rahul Hindocha

Reputation: 215

You can just hardcode the logic and then run this in a loop.

l = ['your name', 'mother', 'age', '43']
d = {}
d[l[0]] = {
    l[1]: {
        l[2]: l[3]
        }
    }

Upvotes: 0

Wizard.Ritvik
Wizard.Ritvik

Reputation: 11710

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'}}}

Upvotes: 2

Related Questions