Convert a list into a nested Dict

I need to convert a list into a nested Dict in python. Like this:

list = [1, 2, 3, 3, 4]
value = 5

Converted to this:

dict = {1: {2: {3: {4: 5}}}}

I have already tried

new_dict = current = {}
for number in list:
   current[number] = {}
   current = current[number]   

But how you can see that the value is not in the Dict. How can I fix it?

>Solution :

One way to do:

value = 5
my_dict = {}
my_list = [1, 2, 3, 3, 4]
for e in reversed(my_list):
    if not e in my_dict:
        my_dict = {e:value}
        value = {e:value}

print(my_dict):

{1: {2: {3: {4: 5}}}}

Leave a Reply