简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM