在python / django中有列表字典的类别标题

时间:2013-03-07 22:59:16

标签: python django

假设我在django中有以下列表字典:

items = [{'category':'apple','item':'granny smith'},
 {'category':'apple','item':'cox'},
 {'category':'apple','item':'pixie'},
 {'category':'orange','item':'premier'},
 {'category':'orange','item':'queen'},
 {'category':'orange','item':'westin'},
 {'category':'tea','item':'breakfast'},
 {'category':'tea','item':'lady grey'},
 {'category':'tea','item':'builders'},
 {'category':'coffee','item':'colombia'},
 {'category':'coffee','item':'kenya'},
 {'category':'coffee','item':'brazil'}]

如何让它在模板中显示如下:

apple:
    granny smith
    cox
    pixie
orange:
    premier
    queen
    ...

我应该在视图中还是在模板中执行此操作(我的意思是逻辑)?如果我只想显示列表的前五个,会发生什么?我需要一个不会给我空类别的解决方案

修改

我必须承认,这是对我的问题的过度简化,我处理的实际列表已按datetime排序,如下所示:

items.sort(key=lambda item:item['created'], reverse=True)

1 个答案:

答案 0 :(得分:2)

使用defaultdict按类别对所有项目进行分组的解决方案:

from collections import defaultdict

items = [{'category':'apple','item':'granny smith'},
 {'category':'apple','item':'cox'},
 {'category':'apple','item':'pixie'},
 {'category':'orange','item':'premier'},
 {'category':'orange','item':'queen'},
 {'category':'orange','item':'westin'},
 {'category':'tea','item':'breakfast'},
 {'category':'tea','item':'lady grey'},
 {'category':'tea','item':'builders'},
 {'category':'coffee','item':'colombia'},
 {'category':'coffee','item':'kenya'},
 {'category':'coffee','item':'brazil'}]

result = defaultdict(list)
for item in items:
    result[item['category']].append(item['item'])

在模板中:

{% for key, values in result.items() %}
    <span>{{key}}</span>
    <ul>
    {% for item in values %}
        <li>{{item}}</li>
    {% endfor %}
    </ul>
{% endfor %}