I would like to convert a nested list like this:
JavaScript
x
2
1
["Pie", ["Sugar", "Biscuit", ["Egg"] ], "Cocoa", []]
2
to a nested dictionary like this:
JavaScript
1
2
1
{ "Pie": { "Sugar": {}, "Biscuit": { "Egg": {} } }, "Cocoa": {} }
2
with max recursion.
Possible variants of nested list:
JavaScript
1
2
1
["Pie", ["Sugar", "Biscuit", ["Egg"], "Something", ["Something2"] ], "Cocoa", []]
2
JavaScript
1
2
1
["Pie", ["Sugar", ["Biscuit"], "Another something", ["Egg"], "Something", ["Something2"] ], "Cocoa", ["One", ["Nested1"], "Two", ["Nested2"] ]]
2
INCORRECT variants:
JavaScript
1
2
1
["Pie", [["Sugar"], "Biscuit", ["Egg"], "Something", ["Something2"] ], "Cocoa", []]
2
JavaScript
1
2
1
[["Pie"], ["Sugar", "Biscuit", ["Egg"], "Something", ["Something2"] ], "Cocoa", []]
2
Advertisement
Answer
Here is one approach (see comments in the code for details):
JavaScript
1
19
19
1
l = ["Pie", ["Sugar", "Biscuit", ["Egg"] ], "Cocoa", []]
2
3
def to_nested(l):
4
out = {}
5
skip = False
6
for i, e in enumerate(l): # enumerate to keep track of position
7
if skip: # we already used this item as value, skip it
8
skip = False
9
continue
10
# ensure we have a next item and that it is a list
11
if i+1<len(l) and isinstance(l[i+1], list):
12
skip = True # flag item to be skipped as key
13
out[e] = to_nested(l[i+1])
14
else: # add a default empty dictionary as value
15
out[e] = {}
16
return out
17
18
out = to_nested(l)
19
output:
JavaScript
1
2
1
{'Pie': {'Sugar': {}, 'Biscuit': {'Egg': {}}}, 'Cocoa': {}}
2