How to loop dictionary with multiple values in Jinja?

Question:

I have a dictionary like so: {'a': [Object, 0], 'b': [Object, 1] } Where object is an actual object with multiple attributes. I’m trying to a check on each key to see if the second value in the array is a 0 or 1. If it is a 1, then I’ll display “Hello” if it’s a 0, I’ll display “Goodbye” Here’s what I have so far that doesn’t seem to work:

{% for key in follower_list %}
   {% if follower_list[key][1] == 0 %}
        <p>Hello</p>
   {% else %}
         <p>Goodbye</p>
{% endif %}

Here, follower_list is the dictionary. I’m getting an error by my IDE saying operator expected where follower_list[key][1] is there a way I can do this type of logic in Jinja?

Asked By: user2896120

||

Answers:

Try using this method:

{% for key, value in follower_list.items() %}
    {% key %}
    {% value %}
{% endfor %}

This calls the items function on the dictionary letting you iterate through all the keys and values of the dictionary.

Use iteritems to iterate through your dictionary:

{% for key, value in follower_list.items %}
    {% if value.1 == 0 %}
        <p>Hello</p>
    {% else %}
        <p>Goodbye</p>
{% endfor %}

Check this docs.

Answered By: Lev Zakharov
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.