Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 388
nookie Avatar asked Jan 09 '12 13:01

nookie


2 Answers

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)
like image 185
NPE Avatar answered Sep 25 '22 02:09

NPE


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)
like image 23
bpgergo Avatar answered Sep 23 '22 02:09

bpgergo