Sort dict of dict in jinja2 loop

How can I sort the dict as

my_dict = {
    'abc': {'name': 'B', 'is_sth': True},
    'xyz': {'name': 'A', 'is_sth': True}
}

name in jinja?

I tried {% for id, data in my_dict|dictsort(by='value') if data.is_sth %}, but it does not work as I expect.

+4
source share
2 answers

Decision:

my_dict.items()|sort(attribute='1.name')

+3
source

if you can live with ordering your data outside of jinja and then just display it, you can do this:

from jinja2 import Template
from collections import OrderedDict

tmplt = Template('''
{% for id, data in od.items() if data.is_sth %}
{{id}}, {{data}}
{% endfor %}
''')

od = OrderedDict((key, value) for key, value in
                 sorted(my_dict.items(), key=lambda x: x[1]['name']))

print(tmplt.render(od = od))

which gives:

xyz, {'name': 'A', 'is_sth': True}

abc, {'name': 'B', 'is_sth': True}

besides this, you may have to create a custom filter .

0
source

Source: https://habr.com/ru/post/1675345/


All Articles