从数据库查询中填充嵌套字典

3

我在数据库中有一些数据,看起来像这样(简化)

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
我建议您使用pandas,分层索引可以实现您想要的功能。http://pandas.pydata.org/pandas-docs/dev/indexing.html#hierarchical-indexing-multiindex - HYRY
1个回答

4
您可以将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

从collections导入默认字典(defaultdict)。 - dmg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接