2017-07-24 64 views
3

如何將["one","two","three","four"]這樣的列表變成類似{"one": {"two": {"three":{"four"}}}}的列表,其中列表中的每個項目都是字典中其他元素的後代?我認爲它可以在遞歸函數中完成,但我不知道如何。如何將列表轉換爲層次結構dict

這是我的嘗試:

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

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

print(d) 

謝謝!

+0

注意,你最後一個元素是*'set' *而不是'dict'。 –

+0

由於python沒有tail-call優化,當輸入的長度太長以至於不能遞歸時,您可能需要重構爲非遞歸或正確處理。見https://stackoverflow.com/questions/13591970/does-python-optimize-tail-recursion – Novaterata

回答

5

遞歸溶液

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}}}} 
+0

謝謝!這工作 – Kremla

0
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'}}}}} 
2

得到的,如果你想要的結構看起來像下面

{'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) 
+0

是的,看到了。感謝您的更新,我會更新我的帖子。 – Kulix

+0

@CoryKramer我認爲這個陳述仍然有效:我希望OP不打算把一組作爲最後一個值。 – TemporalWolf

2

如果你喜歡一個非遞歸解決方案:

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可能無法正常運作。

相關問題