【发布时间】:2018-08-02 11:32:47
【问题描述】:
我对 jinja 中的 groupby 函数有以下问题:
我有一个字典列表,其中每个里面的一个键是[Tech]:**some tech value**
我想以自定义方式进行排序和分组,假设我有
tech_order = [tech2, tech5, tech1, tech3, tech4] #these values are arbitrary just for example
当我只使用 python 执行此操作时
def custom_sort_list_dictated(Dict, Key, list_order):
Dict = Dict.sort(key=lambda k:list_order.index(k[Key]))
#Written as function because I pass it later in jinja2.Environment.globals.update()
custom_sort_list_dictated(My_list_of_dicts, 'Tech', tech_order)
#This works and sorts my dictionaries correctly
for key, value in itertools.groupby(Anforderungen, key=itemgetter('Tech')):
Val_list.append(list(value)) # Store group iterator as a list
Key_list.append(key)
在 python 中使用itertools.groupby 将根据我的tech_order 列表对我的自定义排序字典进行分组,并将它们分组以保持顺序。
但在 jinja2 中并非如此,我有以下模板:
{{ custom_sort_list_dictated(My_list_of_dicts, 'Tech', tech_order) or '' }}
{% for Tech, group_by_tech in My_list_of_dicts|groupby('Tech') %}
{{ jinja_append_array(Val_Array, list(group_by_tech)) or '' }}
{{ jinja_append_array(Key_Array, Tech) or '' }}
{% endfor %}
但是 jinja2 中的 groupby 按字母顺序对我的字典进行排序,这与 python 中的 itertools.groupby 不同。有没有办法不发生这种情况?
我知道问题是 jinja2 groupby 因为只是打电话:
{% for Tech, group_by_tech in My_list_of_dicts|groupby('Tech') %}
{{ Tech + " ~~ " }}
{% endfor %} #This prints my techs in alphabetical order which is not consistent with itertools.groupby
PS:jinja_append_array 和 custom_sort_list_dictated 使用 jinja2.Environment.globals.update() 从 python 传递到 jinja
【问题讨论】:
标签: python dictionary jinja2