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)
这篇关于如何制作嵌套字典并动态追加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!