如何创建嵌套字典并动态添加数据

6 投票
5 回答
13271 浏览
提问于 2025-04-17 09:51

我有一个循环,它给我提供了三个变量。

matteGroup
matteName
object

我想创建一个嵌套字典来保存所有这些数据,像这样:

dictionary{matteGroup: {matteName: obj1, obj2, ob3} }

我正在逐个检查这些对象,所以我想在不存在的情况下创建matteGroup,如果matteName不存在也要创建,然后再添加对象的名称。我尝试了很多方法,比如普通字典、默认字典,还有一些我在网上找到的自定义类,但我一直没能做到这一点。我有一个不错的嵌套结构,但无法添加,或者反过来也一样。

这是我的循环:

    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)

这样我得到了两个单独的字典,但这并不是很有用!有什么建议吗?

谢谢!

5 个回答

2

看看collections模块里的defaultdict

这里有一个简单的例子,跟你想要的很像:

>>> 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(<function <lambda> at 0x7ffcb5ace9b0>, {'group1': defaultdict(<type 'list'>, {'name2': [4, 5], 'name1': [1, 2, 3]}), 'group2': defaultdict(<type 'list'>, {'name1': [6]})})

所以,你只需要这个:

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

如果我理解你的需求没错的话:

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)
4

试试这样做

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)

撰写回答