1

I would like to do a jinja for loop on my dictionary and sort by the value of name

dict example

    things:
      1:
        name: afoo
      2:
        name: zfoo
      3:
        name: bfoo
      4:
        name: cfoo

Jinja gathered from documentation

{%- for thing, property in things|dictsort('name') %}
  foo "{{ property.name }}" bar
{%- endfor %}

results in

foo afoo bar
foo zfoo bar
foo bfoo bar
foo cfoo bar

I've tried quite a few iterations of dictsort() and sort() using different values in place of name like property.name or thing.name and had no luck, obviously I'm missing something, the documentation on this sort function is pretty lite.

Preston
  • 1,300
  • 1
  • 17
  • 32
  • Question is a dupe, search never pulled up the other question for whatever reason. Here's how I solved mine. {%- for thing, property in things.items()|sort(attribute='1.name') %} – Preston Aug 18 '21 at 18:01

1 Answers1

1
{%- for thing, property in things.items()|sort(attribute='1.name') %} 

solved the problem.

Sort dict of dict in jinja2 loop

Preston
  • 1,300
  • 1
  • 17
  • 32
  • This example helped me to understand. I replaced thing, property to key,value. Things to mydict and you just have to change "name" to the value you need to sort – Lexsoul Dec 17 '22 at 04:07