How to convert a list to a dict hierarchy
How would I turn a list sort of ["one","two","three","four"]
into something like {"one": {"two": {"three":{"four"}}}}
, where each item in the list would be a descendant of another item in the dictionary? I think it can be done in a recursive function, but I'm not sure how to do it.
This is what I tried:
l = ["one","two","three","four"]
d = {}
for v in l[:-1]:
d[v] = {l}
d = d[v]
print(d)
Thank!
source to share
Recursive solution
def dictify(d):
if len(d) == 1:
return {d[0]}
else:
return {d[0]: dictify(d[1:])}
for example
>>> dictify(["one","two","three","four"])
{'one': {'two': {'three': {'four'}}}}
Note that in the above solution, the innermost object is actually the one set
, not dict
. If you want all objects to be dict
, you can change the solution to
def dictify(d):
if len(d) == 1:
return {d[0]: None}
else:
return {d[0]: dictify(d[1:])}
Result
>>> dictify(["one","two","three","four"])
{'one': {'two': {'three': {'four': None}}}}
source to share
If you want the structure to look like this
{'one': {'two': {'three': {'four': None}}}}
You can create this with something like this. This solution uses recursion.
arr = ["one", "two", "three", "four"]
def gen(arr):
if len(arr) == 0:
return None
else:
key = arr.pop(0)
val = gen(arr)
dict = {}
dict[key] = val
return dict
print gen(arr)
source to share
If you prefer a non-recursive solution:
def endeepen(lst):
old = None
for v in lst[::-1]:
ret = {}
ret[v] = old
old = ret
return ret
It just repeats the list in reverse order and buries each dct as the value of the previous elements:
>>> endeepen(l)
{'one': {'two': {'three': {'four': None}}}}
If you really want the last element to be a set, you can do it with a slight adjustment:
def endeepen(lst):
old = {lst[-1]}
for v in lst[len(lst) - 2::-1]:
ret = {}
ret[v] = old
old = ret
return ret
which then gives:
>>> endeepen(l)
{'one': {'two': {'three': set(['four'])}}}
Note. In both cases, I did not use boundary conditions, so empty or very short lists len(1) <= 1
may not work correctly.
source to share