作者:舍w不e得i | 来源:互联网 | 2023-01-28 16:01
如何将列表["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)
谢谢!
1> CoryKramer..:
递归解决方案
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'}}}}
注意在上面的解决方案中,最内层的对象实际上是a set
,而不是a 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}}}}