*非常*嵌套的元组理解

2rs*_*2ts 0 python python-2.7 dictionary-comprehension

我有这样的数据(是的,这些元组保证有5个元素):

ts = ([('a','b','c','d','e'), ('v','w','x','y','z'),
       ('f','g','h','i','j'), ('a','foo','bar',1,2),
       ('f','g','baz',1,3), ('f','g','baz',3,4)])
Run Code Online (Sandbox Code Playgroud)

我正在尝试将其解析为嵌套字典结构,如下所示:

d = {
    'a': {
        'b': {
            'c': [('d','e')]
        },
        'foo': {
            'bar': [(1,2)]
        }
    },
    'f': {
        'g': {
            'h': [('i', 'j')],
            'baz': [(1,3), (3,4)]
        }
    },
    'v': {
        'w': {
            'x': [('y', 'z')]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所拥有的; 它似乎工作正常:

>>> d = {}
>>> for t in ts:
...     if t[0] not in d:
...         d[t[0]] = {t[1]: {t[2]: [(t[3], t[4])]}}
...     elif t[1] not in d[t[0]]:
...         d[t[0]][t[1]] = {t[2]: [(t[3], t[4])]}
...     elif t[2] not in d[t[0]][t[1]]:
...         d[t[0]][t[1]][t[2]] = [(t[3], t[4])]
...     else:
...         d[t[0]][t[1]][t[2]].append((t[3],t[4]))
... 
>>> d
{'a': {'b': {'c': [('d', 'e')]}, 'foo': {'bar': [(1, 2)]}}, 'f': {'g': {'h': [('i', 'j')], 'baz': [(1, 3), (3, 4)]}}, 'v': {'w': {'x': [('y', 'z')]}}}
Run Code Online (Sandbox Code Playgroud)

当我尝试这种理解时,当然,一些值被覆盖了:

>>> {t[0]: {t[1]: {t[2]: [(t[3],t[4])]}} for t in ts}
{'a': {'foo': {'bar': [(1, 2)]}}, 'f': {'g': {'baz': [(3, 4)]}}, 'v': {'w': {'x': [('y', 'z')]}}}
Run Code Online (Sandbox Code Playgroud)

你真的不想看到这个结果:

>>> {t[0]: {t[1]: {t[2]: [(t[3],t[4])] for t in ts} for t in ts} for t in ts}
Run Code Online (Sandbox Code Playgroud)

我如何正确地写这个词典理解?

编辑:对不起,我忘了提一下 - 我需要在一天结束时成为常规词典(它NSDictionary最终会转换为通过PyObjC).

Blc*_*ght 5

我根据需要设置字典自动构建自己的嵌套结构:

from collections import defaultdict

dct = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
Run Code Online (Sandbox Code Playgroud)

然后只需将2元组添加到右侧列表中:

for a, b, c, d, e in ts:
    dct[a][b][c].append((d, e))
Run Code Online (Sandbox Code Playgroud)

如果不同层次的索引有含义,我会使用优于名称a,b,c虽然.