Python 在 jinja2 循环中对 dict 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12767550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort dict in jinja2 loop
提问by Syl
I'm still learning jinja2 and flask and I'm having a difficulty using dictsort in jinja2.
我仍在学习 jinja2 和烧瓶,并且在 jinja2 中使用 dictsort 时遇到了困难。
So I'm passing this dict into a jinja2 template:
所以我将这个 dict 传递到一个 jinja2 模板中:
{'PEDD United': {'id': 37828, 'rank': 12, 'totalpts': 307},'Fc Mbonabushia': {'id': 205633, 'rank': 6, 'totalpts': 356},'FC Slurp': {'id': 933573, 'rank': 11, 'totalpts': 312},'KFC_Overijse': {'id': 38861, 'rank': 5, 'totalpts': 362},'Fc Paris': {'id': 1538051, 'rank': 2, 'totalpts': 396}}
What I want is create a table that is sorted by the value of the key 'totalpts'. I tried all sort of things and it just doesn't take totalpts into account when "sorting".
我想要的是创建一个按键“totalpts”的值排序的表。我尝试了各种方法,但在“排序”时并没有考虑总数。
Here's one of my code:
这是我的代码之一:
<table class="table table-bordered">
{% for team in league %}
<tr>
<td>{{team}}</td>
{% for data in league[team]|dictsort(league[team]['totalpts']) %}
<td>{{ league[team]['totalpts'] }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
by it doesn't sort anything in this case... Just print the value in the table without any order...
在这种情况下,它不会对任何内容进行排序......只需在没有任何顺序的情况下打印表中的值......
Anyone can help me out?
任何人都可以帮助我吗?
thanks
谢谢
采纳答案by Anuj Gupta
The way you're doing this will not work, because as soon as you use {% for team in league %}, you're already using the unsorted dict and extracting the key,value pair from it.
你这样做的方式是行不通的,因为一旦你使用{% for team in league %},你就已经在使用未排序的字典并从中提取键值对。
I think |dictsortmay not be able to help you in this case because you cannot sort by either key or value, but by the value's (sub-dict's) value for 'totalpts'.
我认为|dictsort在这种情况下可能无法帮助您,因为您不能按键或值排序,而是按“totalpts”的值(子字典)值排序。
Instead, you should sort this dictionary beforepassing it to the template, in the following way:
相反,您应该在将字典传递给模板之前对其进行排序,如下所示:
>>> from collections import OrderedDict
>>> league={'PEDD United': {'id': 37828, 'rank': 12, 'totalpts': 307},'Fc Mbonabushia': {'id': 205633, 'rank': 6, 'totalpts': 356},'FC Slurp': {'id': 933573, 'rank': 11, 'totalpts': 312},'KFC_Overijse': {'id': 38861, 'rank': 5, 'totalpts': 362},'Fc Paris': {'id': 1538051, 'rank': 2, 'totalpts': 396}}
>>> league = OrderedDict(sorted(league.items(), key= lambda x: x[1]['totalpts'], reverse=True))
>>> print league
OrderedDict([('Fc Paris', {'id': 1538051, 'rank': 2, 'totalpts': 396}), ('KFC_Overijse', {'id': 38861, 'rank': 5, 'totalpts': 362}), ('Fc Mbonabushia', {'id': 205633, 'rank': 6, 'totalpts': 356}), ('FC Slurp', {'id': 933573, 'rank': 11, 'totalpts': 312}), ('PEDD United', {'id': 37828, 'rank': 12, 'totalpts': 307})])
To sort the dict, we convert it into a list of tuples of (key ,value) using .items(). Assuming x is one such tuple, x[1] contains the dictionary with the 'totalpts' key.
为了对 dict 进行排序,我们使用 将其转换为 (key ,value) 的元组列表.items()。假设 x 是一个这样的元组, x[1] 包含带有 'totalpts' 键的字典。
>>> league.items()[0]
('Fc Paris', {'id': 1538051, 'rank': 2, 'totalpts': 396}) # = x
So now we sort the tuples usingx[1]['totalpts'], using reverse=Truefor a decreasing order.
所以现在我们使用x[1]['totalpts'], usingreverse=True对元组进行降序排序。
A dict itself cannot be sorted, it is an unordered data type - You can either use an OrderedDict, or you can simply use tuples:
dict 本身不能排序,它是一种无序数据类型 - 您可以使用 an OrderedDict,也可以简单地使用元组:
>>> sorted(league.items(), key= lambda x: x[1]['totalpts'], reverse=True)
[('Fc Paris', {'id': 1538051, 'rank': 2, 'totalpts': 396}), ('KFC_Overijse', {'id': 38861, 'rank': 5, 'totalpts': 362}), ('Fc Mbonabushia', {'id': 205633, 'rank': 6, 'totalpts': 356}), ('FC Slurp', {'id': 933573, 'rank': 11, 'totalpts': 312}), ('PEDD United', {'id': 37828, 'rank': 12, 'totalpts': 307})]
回答by Andy Hayden
回答by dpr
You can sort a dict's items using the normal sortfilter.
您可以使用普通sort过滤器对 dict 的项目进行排序。
To sort by key use attribute=0:
要按键排序,请使用attribute=0:
{% for key, value in data.items()|sort(attribute='0') %}
{{ key }}: {{ value }}
{% endfor %}
To sort by value use attribute=1
按值排序 attribute=1
{% for key, value in data.items()|sort(attribute='1') %}
{{ key }}: {{ value }}
{% endfor %}
To sort by an attribute of the values use attribute=1.name
要按值的属性排序,请使用 attribute=1.name
{% for key, value in data.items()|sort(attribute='1.name') %}
{{ key }}: {{ value }}
{% endfor %}
That is the loop in the question will translate to
那是问题中的循环将转化为
{% for team_name, team_attrs in league.items()|sort(attribute='1.totalpts') %}
<td>{{ team_attrs.totalpts }}</td>
{% endfor %}

