2013-06-20 81 views
1

我打算在不知道層次和節點的確切數量之前使用python dict創建一棵樹。我如何使用Python dict動態創建一棵樹

例如我要循環許多具有3個屬性的項目:尺寸,顏色和重量。在每一個循環我做以下事情

item_data = {} 
for item in items: 
    size, color, weight = item.get_attr() 
    if size not in item_data: 
     item_data[size] = {} 
    if color not in item_data[size]: 
     item_data[size][color] = {} 
    if weight not in item_data[size][color]: 
     item_data[size][color][weight] = [] 
    # Do something to the tree... 

最後我得到的字典這樣

item_data == {'L':{ 
        'red':{45:[...], 
         50:[...]}, 
        'green':{ 
         40:[...]}}, 
       'XL':{...}} 

但這不靈活。例如,如果我想添加另一個屬性,如「價格」?如果在上面的代碼中,我必須知道它並添加一個。

我想通過以下方式做,但不知道怎麼做,在幾行

attrs = [item.get_attr()] 
for attr in attrs: 
    # Create the tree here.. 

提前感謝!

回答

1

看看networkx在這裏是相關的。否則,這是一個基本版本,擴展了使用attr循環的想法(代碼未經測試)。

for item in items: 
    tree = item_data 
    for i,attr in enumerate(item.get_attr()): 
     if attr not in tree.keys(): 
      if i<len(item.get_attr())-1: 
       tree[attr] = {} 
      else: 
       tree[attr] = [] 
     else: 
      tree = tree[attr] 
    # do something to the tree 
+0

它的工作原理!只有很小的區別是最後一個不需要,因爲樹節點總是需要進入下一層。謝謝! –

+0

對不起。我寫了這段代碼。 http://ideone.com/7JvBub它不起作用。它說'AttributeError:Item實例沒有屬性'get_attr''哪種類型的對象可以與'get_attr'一起使用? – thefourtheye

+0

我以爲'get_attr'是用戶定義的函數。如果您打算使用內置的'getattr'函數,則語法是'getattr(obj)'。 – Nik