How to make a nested dictionary and dynamically append data(如何制作嵌套字典并动态追加数据)
问题描述
我有一个循环给我三个变量
I have a loop giving me three variables
matteGroup
matteName
object
我想制作一个包含所有数据的嵌套字典,例如:
I would like to make a nested dicionary holding all the data like:
dictionary{matteGroup: {matteName: obj1, obj2, ob3} }
我正在一个一个地检查对象,所以我想创建 matteGroup 如果它不存在,创建 matteName 如果它不存在并且然后创建或附加对象的名称.我尝试了很多解决方案,如普通词典、defaultdict 和我在网上找到的一些自定义类,但我一直无法正确完成.我有一个很好的嵌套,我无法追加,反之亦然.
I am checking the objects one by one so I would like to create the matteGroup if it doesn't exist, create the matteName if it doesn't exixst and then create or append the name of the object.
I tryed a lot of solution like normal dictionaries, defaultdict and some custom classes I found on the net, but I haven't been able to do it properly. I have a nice nesting I am not able to append, or vice versa.
这是循环
dizGroup = {}
dizName = {}
for obj in mc.ls(type='transform'):
if mc.objExists(obj + ('.matteGroup')):
matteGroup = mc.getAttr(obj + ('.matteGroup'))
matteName = mc.getAttr(obj + ('.matteName'))
if matteGroup not in dizGroup:
dizGroup[matteGroup] = list()
dizGroup[matteGroup].append(matteName)
if matteName not in dizName:
dizName[matteName] = list()
dizName[matteName].append(obj)
这样我分别得到了两个字典,但不是很有用!有什么提示吗?
with this I get the two dictionaries separately, but is not so useful! Any hint?
谢谢
推荐答案
尝试这样的事情
dizGroup = {}
for obj in mc.ls(type='transform'):
if mc.objExists(obj + ('.matteGroup')):
matteGroup = mc.getAttr(obj + ('.matteGroup'))
matteName = mc.getAttr(obj + ('.matteName'))
if matteGroup not in dizGroup:
dizGroup[matteGroup] = {}
if matteName not in dizGroup[matteGroup]:
dizGroup[matteGroup][matteName] = []
dizGroup[matteGroup][matteName].append(obj)
这篇关于如何制作嵌套字典并动态追加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何制作嵌套字典并动态追加数据
基础教程推荐
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
