Convert a list into a nested Dict

Question:

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?

Asked By: Andree098766

||

Answers:

EDITS : Changed variable name and keyword

  1. Not sure what value and new_dict is used for

  2. Never name your variables with a built-in type (don’t use list)

  3. For each number you’re creating an empty dictionary and then reassigning current to it

    Basically current[1]={} followed by current=current[1] will obviously always end up with current={}

One way to do this :

myList = [1, 2, 3, 4]   

First create just the inner most dictionary with the last element from myList and value

current_dict = {myList[-1]: value}   

new_dict = {}  

Now loop through each number in the reverse of the list excluding the first one ( 3,2,1)

for number in myList[::-1][1:]:
    new_dict[number] = current_dict
    current_dict = new_dict
    new_dict = {}

This would look like this :

new_dict[3] = {4:5}           | current_dict ={3:{4:5}} 
new_dict[2] = {3:{4:5}}       | current_dict ={2:{3:{4:5}}}
new_dict[1] = {{2:{3:{4:5}}}  | current_dict ={1:{2:{3:{4:5}}}}

current_dict would have the final result

print(current_dict)   #{1: {2: {3: {4: 5}}}}
Answered By: Sruthi

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}}}}
Answered By: SomeDude
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.