Reputation: 19
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?
Upvotes: 0
Views: 78
Reputation: 3018
EDITS : Changed variable name and keyword
Not sure what value
and new_dict
is used for
Never name your variables with a built-in type (don't use list
)
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}}}}
Upvotes: 2
Reputation: 14238
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}}}}
Upvotes: 1