我需要生成这样的字典:
<代码>{'新环境':{'新项目':{'新比较':{实例":[],'n_thing': '新事物'}}}}
来自一个元组,像这样:('newEnv','newProj','newComp','newThing')
但前提是它不存在.所以,我尝试了这个:
myDict = {}(env,proj,comp,thing) = ('newEnv','newProj','newComp','newThing')如果 env 不在 myDict 中:我的字典 [env] = {}如果 proj 不在 myDict[env] 中:myDict[env][proj] = {}如果 comp 不在 myDict[env][proj] 中:myDict[env][proj][comp] = {'n_thing': 东西,'instances': []}
这非常有效,但不确定它的效率如何,或者我是否应该这样做.有什么建议)??
可以使用循环(只有前 3 个键,newThing
不是链中的键):
myDict = {}路径 = ('newEnv','newProj','newComp')当前 = 我的字典对于路径中的键:当前 = current.setdefault(key, {})
其中 current
最终成为最里面的字典,让您在其上设置 'n_thing'
和 'instances'
键.p>
您可以使用 reduce()
将其折叠成单行:
myDict = {}路径 = ('newEnv','newProj','newComp')减少(lambda d,k:d.setdefault(k,{}),路径,myDict)
reduce
调用返回最里面的字典,因此您可以使用它来分配最终值:
myDict = {}路径 = ('newEnv','newProj','newComp')inner = reduce(lambda d, k: d.setdefault(k, {}), path, myDict)inner.update({'n_thing': 'newThing', 'instances': []})
I need to generate a dictionary like this:
{
'newEnv': {
'newProj': {
'newComp': {
'instances': [],
'n_thing': 'newThing'
}
}
}
}
from a tuple, like this: ('newEnv','newProj','newComp','newThing')
but only if that doesn't already exists. So, I tried this:
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': []}
which is pretty much working but not sure how efficient is that or if I should be doing this way at all. Any suggestion(s)??
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': []})
这篇关于使用列表/元组元素作为键创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!