轻松构建一个词典或词典的词典
问题描述:
使用python3,我必须建立一个列表的字典的字典的字典。轻松构建一个词典或词典的词典
我不知道是否有更好的方法做下面的代码做(它看起来像垃圾代码......)
ret = {}
for r in listOfDictionnariesFromMongoDatabase:
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)
感谢您的帮助。
答
制作复杂的数据结构并不是很好的做法。我建议使用一个简单的字典,其中键是元组。因此,每个键都是多个键的元组,每个元素都可以通过使用适当的元组键来访问。
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)
答
偷"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
是的。 [collections.defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict) – CoryKramer 2014-10-08 13:36:46
https://gist.github.com/hrldcpr/2012250 – 2014-10-08 13:55:32