[Answered ]-Using keys() on django template

5👍

{% if dict %}
  {% for key, value in dict.items %}
    list
  {% endfor %}
{endif}

edit:

{% if dict %} is not needed – if given context’s variable is empty (or if it’s empty dict), it silently passes:

  {% for key, value in dict.items %}
    list
  {% endfor %}

-3👍

It is probably because dict is a reserved keyword in Python. Try

{% if d %}
  {% for key in d.keys() %}
    list
  {% endfor %}
{endif}

or simply

{% if d %}
  {% for key in d %}
    list
  {% endfor %}
{endif}

an iterator over a dictionary in python is by default over the keys so you don’t have to specify that you want the keys and not .items() or .values().

Leave a comment