[英]How to transform a list into a hierarchy dict
如何将像["one","two","three","four"]
这样的列表变成{"one": {"two": {"three":{"four"}}}}
列表中的每个项目都是字典中其他元素的后代? 我认为它可以在递归函数中完成,但我不确定如何。
这是我试过的:
l = ["one","two","three","four"]
d = {}
for v in l[:-1]:
d[v] = {l}
d = d[v]
print(d)
谢谢!
递归解决方案
def dictify(d):
if len(d) == 1:
return {d[0]}
else:
return {d[0]: dictify(d[1:])}
例如
>>> dictify(["one","two","three","four"])
{'one': {'two': {'three': {'four'}}}}
注意在上面的解决方案中,最里面的对象实际上是一个set
,而不是一个dict
。 如果您希望所有对象都是dict
那么您可以将解决方案修改为
def dictify(d):
if len(d) == 1:
return {d[0]: None}
else:
return {d[0]: dictify(d[1:])}
导致
>>> dictify(["one","two","three","four"])
{'one': {'two': {'three': {'four': None}}}}
如果您希望结构如下所示
{'one': {'two': {'three': {'four': None}}}}
你可以用这样的东西生成它。 此解决方案使用递归。
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)
如果您更喜欢非递归解决方案:
def endeepen(lst):
old = None
for v in lst[::-1]:
ret = {}
ret[v] = old
old = ret
return ret
只需反向迭代列表并将每个dct作为前面的元素值隐藏:
>>> endeepen(l)
{'one': {'two': {'three': {'four': None}}}}
如果你真的想要最后一个元素是一个集合,你可以通过一个小的修正来做到这一点:
def endeepen(lst):
old = {lst[-1]}
for v in lst[len(lst) - 2::-1]:
ret = {}
ret[v] = old
old = ret
return ret
然后给出:
>>> endeepen(l)
{'one': {'two': {'three': set(['four'])}}}
注意:在这两种情况下,我都没有覆盖边缘条件,所以空(或)非常短的列表len(1) <= 1
可能行为不端。
l = ["one","two","three","four"]
d = {}
d2 = d
for v in l[:-1]:
d2[v] = {}
d2 = d2[v]
d2[l[-2]] = {l[-1]}
print(d)
>>> {'one': {'two': {'three': {'three': {'four'}}}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.