Creating dictionary using list/tuple elements as key(使用列表/元组元素作为键创建字典)
问题描述
我需要生成这样的字典:
<代码>{'新环境':{'新项目':{'新比较':{实例":[],'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': []})
这篇关于使用列表/元组元素作为键创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用列表/元组元素作为键创建字典
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01