Search code examples
pythondictionarynestedmaya

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} }

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.

This is the loop

    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?

Thanks


Solution

  • try something like this

    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)