我需要生成一个这样的字典:
{
'newEnv': {
'newProj': {
'newComp': {
'instances': [],
'n_thing': 'newThing'
}
}
}
}
来自元组的,如下所示:('newEnv','newProj','newComp','newThing')
但仅限于此时尚不存在。所以,我试过这个:
myDict = {}
(env,proj,comp,thing) = ('newEnv','newProj','newComp','newThing')
if env not in myDict:
myDict[env] = {}
if proj not in myDict[env]:
myDict[env][proj] = {}
if comp not in myDict[env][proj]:
myDict[env][proj][comp] = {'n_thing': thing, 'instances': []}
这几乎是有效但不确定效率如何,或者我应该这样做。有什么建议)??
答案 0 :(得分:5)
你可以使用循环(只有前3个键,newThing
不是链中的键):
myDict = {}
path = ('newEnv','newProj','newComp')
current = myDict
for key in path:
current = current.setdefault(key, {})
其中current
最终作为最里面的字典,让您在其上设置'n_thing'
和'instances'
键。
您可以使用reduce()
将其折叠成一行:
myDict = {}
path = ('newEnv','newProj','newComp')
reduce(lambda d, k: d.setdefault(k, {}), path, myDict)
reduce
调用返回最里面的字典,因此您可以使用它来分配最终值:
myDict = {}
path = ('newEnv','newProj','newComp')
inner = reduce(lambda d, k: d.setdefault(k, {}), path, myDict)
inner.update({'n_thing': 'newThing', 'instances': []})
答案 1 :(得分:0)
你可以做一些类似的,也许稍微简单一些,默认的defaultdicts(参见defaultdict of defaultdict, nested进行讨论)
tree = lambda: defaultdict(tree)
base = tree()
for x in mytuple[:-2]:
base = base[x]
base[x] = mytuple[-1]
与martijn非常相似,只是使用默认功能来创建subdicts,而不是直接使用setdefault
。
这也让你直接输入
myDict[env][proj][comp].setdefault('instances', list()).append(queue)
如果那是你真正想要的。 (遗憾的是,没有办法删除setdefault;毕竟,我不知道你是否想要一个列表或词典。你只有一个默认值)....