How to make a nested dictionary and dynamically append data

前端 未结 5 1123
闹比i
闹比i 2021-01-13 02:16

I have a loop giving me three variables

matteGroup
matteName
object

I would like to make a nested dicionary holding all the data like:

5条回答
  •  独厮守ぢ
    2021-01-13 02:45

    Look at the defaultdict in the collections module.

    Here's a simple example that looks like what you're going for:

    >>> from collections import defaultdict
    >>> dizGroup = defaultdict(lambda:defaultdict(list))
    >>> dizGroup['group1']['name1'].append(1)
    >>> dizGroup['group1']['name1'].append(2)
    >>> dizGroup['group1']['name1'].append(3)
    >>> dizGroup['group1']['name2'].append(4)
    >>> dizGroup['group1']['name2'].append(5)
    >>> dizGroup['group2']['name1'].append(6)
    >>> dizGroup
    defaultdict( at 0x7ffcb5ace9b0>, {'group1': defaultdict(, {'name2': [4, 5], 'name1': [1, 2, 3]}), 'group2': defaultdict(, {'name1': [6]})})
    

    So, you should just need this:

    if mc.objExists(obj + ('.matteGroup')):
       matteGroup = mc.getAttr(obj + ('.matteGroup'))
       matteName = mc.getAttr(obj + ('.matteName'))
       dizGroup[matteGroup][matteName].append(obj)
    

提交回复
热议问题