2013-03-01 61 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