2015-09-28 46 views
-2

我已經親子映射如下:的Python:創建嵌套的字典從親子mappping

{4:6, 
6:9, 
7:6, 
5:6, 
8:9, 
11:9, 
10:9, 
12:10, 
13:10} 

我要創建使用上面下面的嵌套詞典:

{"id":9, 
"children":[ 
      {"id":6, 
       "children":[ 
          {"id":4, 
          "children":[]}, 
          {"id":5, 
          "children":[]}, 
          {"id":7, 
          "children":[]}, 
         ] 
       }, 
       {"id":10, 
       "children":[ 
          {"id":12, 
          "children":[]}, 
          {"id":13, 
          "children":[]}, 
         ] 
       }, 
       {"id":11, 
       "children":[] 
       }, 
       {"id":8, 
       "children":[] 
       } 
       ] 
} 

我能弄清楚如何代替鍵值爲「id」和值爲9,6等,我可以做到這一點,我有價值作爲關鍵。請以上述格式幫助我。

+3

如何''的6' 9'父,但' 7'6'的孩子? –

+0

爲什麼不反轉字典...我的意思是交換鍵和值。正如你所說,你可以這樣解決。對? –

+0

@AnandSKumar這些只是ID,可以是任何其他節點的父/子。沒有這樣的順序。這回答了你的問題了嗎? – Shruti

回答

0

我得到了我的查詢解決方案。

我轉換父子映射元組的列表如下:

queue_tuples= [(6,9,1),(11,9,1),(8,9,1),(10,9,1),(5,6,2),(7,6,2),(4,6,2),(12,10,2),(13,10,2)] 
root = 9 

以下是代碼:

pGraph = {"id":root,"children":[]} 

for tuple in queue_tuples: 
    level = tuple[2] 
    g = pGraph["children"] 
    for i in range(level-1): 
     for e in g: 
      if tuple[1]==e["id"]: 
       g = e["children"] 
    flag = 0 
    for e in g: 
     if tuple[0]==e["id"]: 
      flag = 1 
      break 
    if flag==0: 
     g.append({"id":tuple[0],"children":[]}) 
print pGraph