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

Python 从数据库查询填充嵌套字典,python,dictionary,Python,Dictionary,我在数据库中有这样的数据(简化) 我的目标是从该表构建嵌套字典,如下所示: dict = {a: {1: 'abc'}, {2: 'def'}, b: {1: 'ghi'}, {2: 'jkl'}} 在我的真实案例中,我没有更多的嵌套级别。 作为一个数据库查询,我想象我可以逐行执行“for”循环 有什么建议可以用这种方式优雅而有效地填充字典吗?您可以将游标.fetchall()的结果提供给此函数。它处理任意数量的列>=2 def nest(rows): root = {

我在数据库中有这样的数据(简化)

我的目标是从该表构建嵌套字典,如下所示:

dict = {a: {1: 'abc'}, {2: 'def'},
        b: {1: 'ghi'}, {2: 'jkl'}}
在我的真实案例中,我没有更多的嵌套级别。 作为一个数据库查询,我想象我可以逐行执行“for”循环


有什么建议可以用这种方式优雅而有效地填充字典吗?

您可以将
游标.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

我建议你使用熊猫,层次索引可以做你想做的。或
从集合导入defaultdict
:)
import collections

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

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