How to make a nested dictionary and dynamically append data

nookie picture nookie · Jan 9, 2012 · Viewed 11.3k times · Source

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

Answer

NPE picture NPE · Jan 9, 2012

Provided I've understood your requirements correctly:

In [25]: from collections import defaultdict

In [26]: d = defaultdict(lambda: defaultdict(list))

In [30]: for group, name, obj in [('g1','n1','o1'),('g1','n2','o2'),('g1','n1','o3'),('g2','n1','o4')]:
   ....:     d[group][name].append(obj)