2013-03-01 62 views
2

我有一個數據庫,它看起來像這樣(簡體)從數據庫查詢填充嵌套的字典

colA, colB, colC 
'a', 1, 'abc' 
'a', 2, 'def' 
'b', 1, 'ghi' 
'b', 2, 'jkl' 

我的目標是建立從該表中嵌套的字典的數據,看起來像這樣:

dict = {a: {1: 'abc'}, {2: 'def'}, 
     b: {1: 'ghi'}, {2: 'jkl'}} 

我在我的真實情況下有更多的嵌套層次。 作爲數據庫查詢,我想我可以做一個'for'循環行

任何建議以優雅/有效的方式來填充字典這種方式?

+1

我建議你用熊貓,層次索引可以做你想做的。 http://pandas.pydata.org/pandas-docs/dev/indexing.html#hierarchical-indexing-multiindex – HYRY 2013-03-01 11:31:49

回答

3

您可以將cursor.fetchall()的結果提供給此功能。它能夠處理任意數量的列> = 2

def nest(rows): 
    root = {} 
    for row in rows: 
     d = root 
     for item in row[:-2]: 
      d = d.setdefault(item, {}) 
     d[row[-2]] = row[-1] 
    return root 

另一種方法來創建任意深度嵌套的字典是這樣的:

import collections 

def nesteddict(): 
    return collections.defaultdict(nesteddict) 

nd = nesteddict() 
for a, b, c in rows: 
    nd[a][b] = c 
+0

或'from collections import defaultdict' :) – dmg 2013-03-01 11:59:59