如何从嵌套字典中生成单行选择生成器?

时间:2015-11-27 11:31:19

标签: python django

我有这样的结构:

actions = {
    'cat1': {
        'visit': {
            'id': 1,
            'description': 'Desc 1',
            'action': 'Act 1',
        },
    },
    'cat2': {
        'download': {
            'id': 2,
            'description': 'Desc 2',
            'action': 'Act 2',
        },
        'click': {
            'id': 3,
            'description': 'Desc 3',
            'action': 'Act 3',
        },
        ...
    },
    ...
}

以下代码为django选择字段生成元组元组:

CHOICES = []
for a in actions.values():
    for c in a.values():
        CHOICES.append((c['id'], c['description']))

是否可以在嵌套for循环的一行中编写上面的代码?

2 个答案:

答案 0 :(得分:2)

CHOICES = [(c['id'], c['description']) for a in actions.values() for c in a.values()]

答案 1 :(得分:0)

使用map和reduce:

autoSubmit : Specifies whether to submit the original form automatically once the upload and processing have completed. This is true by default.