Mac*_*ers 0 python dictionary tuples python-2.7
我需要生成一个这样的字典:
{
  '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': []}
这几乎是有效但不确定效率如何,或者我应该这样做.有什么建议)??
你可以使用一个循环(只有前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': []})
| 归档时间: | 
 | 
| 查看次数: | 266 次 | 
| 最近记录: |