Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python/django中为列表字典提供类别标题_Python_Django - Fatal编程技术网

在python/django中为列表字典提供类别标题

在python/django中为列表字典提供类别标题,python,django,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','

假设我在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)
用于按类别对所有项目进行分组的解决方案:

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 %}
{%用于键,result.items()中的值%}
{{key}}
    {值%%中的项的百分比}
  • {{item}}
  • {%endfor%}
{%endfor%}
你必须解释一下这里发生了什么。我不敢肯定我understand@Sevenearths
result
是一本类似以下内容的词典:
{'orange':['premier','queen','westin'],'tea':['breaken','lady grey','builders'],…}
。因此,迭代每个键的值,就得到了与每个类别对应的所有项。谢谢。我想我可以根据我的需要来调整它,现在我明白了:)