简体   繁体   English

如何将列表转换为层次结构dict

[英]How to transform a list into a hierarchy dict

How would I turn a list like ["one","two","three","four"] into something like {"one": {"two": {"three":{"four"}}}} where each item in the list would be a descendant of the other element in the dictionary? 如何将像["one","two","three","four"]这样的列表变成{"one": {"two": {"three":{"four"}}}}列表中的每个项目都是字典中其他元素的后代? I think it could be done in a recursive function, but I'm not sure how. 我认为它可以在递归函数中完成,但我不确定如何。

This is what I tried: 这是我试过的:

l = ["one","two","three","four"]
d = {}

for v in l[:-1]:
    d[v] = {l}
    d = d[v]

print(d)

Thanks! 谢谢!

A 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 the in above solution, the inner-most object is actually a set , not a dict . 注意在上面的解决方案中,最里面的对象实际上是一个set ,而不是一个dict If you want all objects to be dict then you can modify the solution to 如果您希望所有对象都是dict那么您可以将解决方案修改为

def dictify(d):
    if len(d) == 1:
        return {d[0]: None}
    else:
        return {d[0]: dictify(d[1:])}

Resulting in 导致

>>> dictify(["one","two","three","four"])
{'one': {'two': {'three': {'four': None}}}}

If you wanted the structure to look like the following 如果您希望结构如下所示

{'one': {'two': {'three': {'four': None}}}}

You could generate that 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)

If you'd prefer a non-recursive solution: 如果您更喜欢非递归解决方案:

def endeepen(lst):
    old = None
    for v in lst[::-1]:
        ret = {}
        ret[v] = old
        old = ret
    return ret

Just iterates the list in reverse and buries the each dct as the previous elements value: 只需反向迭代列表并将每个dct作为前面的元素值隐藏:

>>> endeepen(l)
{'one': {'two': {'three': {'four': None}}}}

If you really want the last element to be a set, you can do so with a minor correction: 如果你真的想要最后一个元素是一个集合,你可以通过一个小的修正来做到这一点:

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 haven't covered edge conditions, so empty or very short lists len(1) <= 1 may misbehave. 注意:在这两种情况下,我都没有覆盖边缘条件,所以空(或)非常短的列表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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM