Arul Moondra
Arul Moondra

Reputation: 141

How to select some keys in a dictionary in jinja2 when iterating over them

I have a dictionary like this

[ { 'a' : "Aa1",
    'b' : "Bb1",
    'c' : "Cc1"
  } ,

  { 'a' : "Aa2",
    'b' : "Bb2",
    'c' : "Cc2"
    'd' :"Dd2"
 } ]

I want to reject some keys while looping through this array of dictionaries. So I want result something like

reject key "a" and "b"

c = Cc1

c = Cc2
d = Dd2

How can I accomplish that

I have tried something like this

{ % for dict in dictionaries % }
     {%- for key,value in dict.items()%}
        {%- if key|rejectattr("a", "b") %}
          {{key}} = {{value }}
        {%- endif%}    
    {% endfor %}
{% endfor % }

However this does not work. Any suggestions.

Upvotes: 2

Views: 3822

Answers (1)

haliphax
haliphax

Reputation: 393

What you're actually saying with your rejectattr filter is "the value of key.a cannot be 'b'", which isn't what you're trying to do. Since you're working directly with the key, it's just a str, and doesn't have any such attribute.

Maybe try using equalto as the test, and reject as the main filter:

{% if key|reject('equalto', 'a')|reject('equalto', 'b') %}

Upvotes: 1

Related Questions