Python - 生成父/子dict结构

时间:2016-10-02 13:14:59

标签: python list python-2.7 dictionary parent-child

我有方法:

@staticmethod
def get_blocks():
    """Public method that can be extended to add new blocks.

    First item is the most parent. Last item is the most child.
        Returns:
            blocks (list)
    """
    return ['header', 'body', 'footer']

正如docstring描述的那样,可以扩展此方法,以特定顺序返回任何类型的块。

所以我想做一个映射,指出哪个块是父/子彼此(只关心"最近"父/子)。

def _get_blocks_mapping(blocks):
    mp = {'parent': {}, 'child': {}}
    if not blocks:
        return mp
    mp['parent'][blocks[0]] = None
    mp['child'][blocks[-1]] = None
    blocks_len = len(blocks)
    if blocks_len > 1:
        mp['parent'][blocks[-1]] = blocks[-2]
        for i in range(1, len(blocks)-1):
            mp['parent'][blocks[i]] = blocks[i-1]
            mp['child'][blocks[i]] = blocks[i+1]
    return mp

如果我们在get_blocks方法中有三个块,那么结果如下:

{
        'parent': {
            'header': None,
            'body': 'header',
            'footer': 'body',
        },
        'child': {
            'header': 'body',
            'body': 'footer',
            'footer': None
        }
    }

嗯它的确有效,但对我来说这有点像黑客。那么也许有人可以提出更好的方法来创建这样的映射? (或者可能有一些用于创建父/子映射的方法?使用不同于我打算使用的结构?)

1 个答案:

答案 0 :(得分:1)

您希望成对循环遍历列表,为您提供自然的父子关系:

zip()

>>> blocks = ['header', 'body', 'footer'] >>> mp = {'parent': {}, 'child': {}} >>> if blocks: ... mp['parent'][blocks[0]] = mp['child'][blocks[-1]] = None ... for parent, child in zip(blocks, blocks[1:]): ... mp['parent'][child] = parent ... mp['child'][parent] = child ... >>> from pprint import pprint >>> pprint(mp) {'child': {'body': 'footer', 'footer': None, 'header': 'body'}, 'parent': {'body': 'header', 'footer': 'body', 'header': None}} 这里将每个块与列表中的下一个块配对。

演示:

deinit