簡體   English   中英

如何將列表轉換為層次結構dict

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM