使用list/tuple元素作为键创建字典

Mac*_*ers 0 python dictionary tuples python-2.7

我需要生成一个这样的字典:

{
  'newEnv': {
     'newProj': {
        'newComp': {
           'instances': [],
           'n_thing': 'newThing'
        }
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

从一个元组,像这样:('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': []}
Run Code Online (Sandbox Code Playgroud)

这几乎是有效但不确定效率如何,或者我应该这样做.有什么建议)??

Mar*_*ers 5

你可以使用一个循环(只有前3个键,newThing不是链中的键):

myDict = {}
path = ('newEnv','newProj','newComp')
current = myDict
for key in path:
    current = current.setdefault(key, {})
Run Code Online (Sandbox Code Playgroud)

其中,current作为最词典结束了,让你设置'n_thing''instances'按键上.

您可以使用reduce()它将其折叠成一个单行:

myDict = {}
path = ('newEnv','newProj','newComp')
reduce(lambda d, k: d.setdefault(k, {}), path, myDict)
Run Code Online (Sandbox Code Playgroud)

reduce调用返回最里面的字典,因此您可以使用它来分配最终值:

myDict = {}
path = ('newEnv','newProj','newComp')
inner = reduce(lambda d, k: d.setdefault(k, {}), path, myDict)
inner.update({'n_thing': 'newThing', 'instances': []})
Run Code Online (Sandbox Code Playgroud)