You can use a loop (with just the first 3 keys, newThing
is not a key in the chain):
myDict = {}
path = ('newEnv','newProj','newComp')
current = myDict
for key in path:
current = current.setdefault(key, {})
where current
ends up as the innermost dictionary, letting you set the 'n_thing'
and 'instances'
keys on that.
You could use reduce()
to collapse that into a one-liner:
myDict = {}
path = ('newEnv','newProj','newComp')
reduce(lambda d, k: d.setdefault(k, {}), path, myDict)
The reduce
call returns the innermost dictionary, so you can use that to assign your final value:
myDict = {}
path = ('newEnv','newProj','newComp')
inner = reduce(lambda d, k: d.setdefault(k, {}), path, myDict)
inner.update({'n_thing': 'newThing', 'instances': []})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…