轻松建立词典或词典的字典

问题描述 投票:0回答:2

使用python3,我必须构建一个列表的字典词典字典。

我想知道是否有更好的方法来执行下面的代码(它看起来像垃圾代码......)

ret = {}
for r in listOfDictionariesFromMongoDatabase:
    a = TheObjectIUse(r)
    sp = a.getSp()
    ex = a.getEx()
    th = a.getTh()
    lo = a.getLo()
    de = a.getDe()
    if not sp in ret:
        ret[sp] = {}
    if not ex in ret[sp]:
        ret[sp][ex] = {}
    if not th in ret[sp][ex]:
        ret[sp][ex][th] = {}
    if not lo in ret[sp][ex][th]:
        ret[sp][ex][th][lo] = []
    ret[sp][ex][th][lo].append(de)
python python-3.x dictionary
2个回答
1
投票

"One-line Tree in Python"窃取页面,您可以创建一个递归定义的defaultdict

# UNTESTED

from collections import defaultdict
def tree():
    return defaultdict(tree)
def tree_as_dict(t):
    try:
        return {k:tree_as_dict(v) for k,v in t.items()}
    except AttributeError:
        return t

ret = tree()
for r in listOfDictionnariesFromMongoDatabase:
    a = TheObjectIUse(r)
    sp = a.getSp()
    ex = a.getEx()
    th = a.getTh()
    lo = a.getLo()
    de = a.getDe()
    ret[sp][ex][th].setdefault(lo, []).append(de)
return tree_as_dict(ret)

当然,任何涉及defaultdict的解决方案都可以重写为使用dict.setdefault,反之亦然:

# UNTESTED
ret = {}
for r in listOfDictionnariesFromMongoDatabase:
    a = TheObjectIUse(r)
    sp = a.getSp()
    ex = a.getEx()
    th = a.getTh()
    lo = a.getLo()
    de = a.getDe()

    d = ret.setdefault(sp, {})
    d = d.setdefault(ex, {})
    d = d.setdefault(th, {})
    l = d.setdefault(lo, [])
    l.append(de)
return ret

0
投票

制作复杂的数据结构并不是一种好的做法。我建议只使用带有元组键的简单字典。因此,每个键都是多个键的元组,每个元素只需使用适当的元组键即可访问。

ret = {}
for r in listOfDictionnariesFromMongoDatabase:
    a = TheObjectIUse(r)
    sp = a.getSp()
    ex = a.getEx()
    th = a.getTh()
    lo = a.getLo()
    de = a.getDe()

    tuple_key = (sp, ex, th, lo)
    if tuple_key not in ret:
        ret[tuple_key] = []
    ret[tuple_key].append(de)
© www.soinside.com 2019 - 2024. All rights reserved.