Search code examples
python-3.xlistdictionaryjinja2

How to count list of dictionaries key's in Jinja


I have list of dictionaries i want to count how many times "P" appears in that dictionaries and update total as key and give value count

{% set my_list = [
  {'key1': "P",'key2': "P",'key3': "P",'key4': "P"},
  {'key1': "P",'key2': "P",'key1': "",'key3': "P",'key4': "P"}, 
  {'key1': "P",'key2': "P",'key3': "",'key4': "P"}
] %}

My code is :

{% for my_dict in my_list %}

  {% set count = 0 %}

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

    {% if value == 'P' %}

      {% set count = count + 1 %}

    {% endif %}

  {% endfor %}

 {% set _ = emp.update({'total': count}) %}  

{% endfor %}


This code is not incrementing count instead of incrementing its giving 0 in all dictionary i don't know how to do it

expecting output :

[
 {'key1': 'P', 'key2': 'P', 'key3': 'P', 'key4': 'P', 'total': 4},
 {'key1': '', 'key2': 'P', 'key3': 'P', 'key4': 'P', 'total': 3},  
 {'key1': 'P', 'key2': 'P', 'key3': '', 'key4': 'P', 'total': 3}
]

Solution

  • The simple {% set %} assignment has limited scope (the current block), you have to use the namespace object instead.

    {% set counter = namespace(p=0) %}
    {% for my_dict in my_list %}
      {% set counter.p = 0 %}{# Reset counter #}
      {% for key, value in my_dict.items() %}
        {% if value == 'P' %}
          {% set counter.p = counter.p + 1 %}
        {% endif %}
      {% endfor %}
      {% set _ = my_dict.update({'total': counter.p}) %}{# Update dictionary with total #}
    {% endfor %}