JokerMartini JokerMartini - 1 year ago 72
Python Question

How to create a nested dictionary from a list in Python?

I have a list of strings:

tree_list = ['Parents', 'Children', 'GrandChildren']

How can i take that list and convert it to a nested dictionary like this?

tree_dict = {
'Parents': {
'Children': {
'GrandChildren' : {}

print tree_dict['Parents']['Children']['GrandChildren']

Answer Source

This easiest way is to build the dictionary starting from the inside out:

tree_dict = {}
for key in reversed(tree_list):
    tree_dict = {key: tree_dict}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download