【发布时间】:2014-01-28 06:50:16
【问题描述】:
我需要生成这样的字典:
{
'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': []}
这非常有效,但不确定它的效率如何,或者我是否应该这样做。有什么建议)??
【问题讨论】:
-
顺便说一句,你的解决方案无论如何都不错。
标签: python python-2.7 dictionary tuples