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