简体   繁体   中英

jinja2: sort dict by defined key order?

So lets say I want to display some data like this:

• b is foo
• a is bar
• c is baz

...but my dataset looks like this (or any other order, since JSON doesn't care):

{
"a": "bar",
"b": "foo",
"c": "baz"
}

How do I tell Jinja2 to display my data with keys always in bac order)? And what if I'm not sure if the element c will always be present?

I thought it would be something like this, to no avail:

<ul>
{% for key, value in my_dict.items()|dictsort(by=['b', 'a']) %}
    <li>{{ key }} is {{ value }}</li>
{% endfor %}
</ul>

You could loop through a hard-coded list of keys:

<ul>
{% for key in ('b', 'a', 'c') %}
    {% if key in my_dict %}
    <li>{{ key }} is {{ my_dict[key] }}</li>
    {% endif %}
{% endfor %}
</ul>

Non-existing keys are handled by the if test.

Python dicts are not ordered, maybe you can use OrderedDict from collections :

import collections

my_dict = {
    "a": "bar",
    "b": "foo",
    "c": "baz"
}
my_ord_dict = collections.OrderedDict(my_dict)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM