Master For Loop with Dictionary Object in Django Templates

Django templates provide a flexible and intuitive way to work with data, including dictionaries. If you want to iterate over the key-value pairs of a dictionary in your Django template, you find that Django’s template engine offers powerful tools to accomplish this. In this blog, we’ll explore how to effectively use for loops to iterate over dictionaries in Django templates.

Why Loop Over Dictionaries in Django Templates?

Dictionaries are common data structures in Python and you might find yourself needing to loop through dictionary items to display data in your templates. For example may want to render a table or list of items with their associated values, where each item corresponds to a dictionary key

In Django templates, iterating over dictionaries is common task when rendering dynamic content. By utilizing the {% for %} template tag you can loop through dictionary items and display them in your templates.

Let’s dive into the steps to achieve this in Django templates.

Using For Loops in Django Templates

Django’s template language is designed to be readable and expressive. To loop over a dictionary in a Django template, follow these steps:

1. Access the Dictionary in Your Template:

Ensure that the dictionary you want to loop through is aavailable in the template context. You can pass it from your views, or if you’re working with a Django model you can access dictionary-like attributes.

2. Utilize the {% for %} Template Tag:

The {% for %} template tag is used for creating loops in Django templates. To loop over a dictionary, you can nest it within your HTML structure.

<ul>
    {% for key, value in my_dict.items %}
        <li>{{ key }}: {{ value }}</li>
    {% endfor %}
</ul>

In this example, we use {% for key, value in my_dict.items %} to loop over the dictionary’s items, where key is the dictionary key, and value is the corresponding value.

3. Display the Dictionary Items:

Within the loop, you can access the key and value variables to display the dictionary’s key-value pairs.

Advanced Techniques

  • Loop Counter: If you need a counter while looping, you can use {% for key, value in my_dict.items %} {{ forloop.counter }}. {{ key }}: {{ value }} {% endfor %} to display an incremental count.
  • Filtering: You can apply filters to values as you loop through the dictionary. For instance, {% if value|length > 10 %} would display items with values longer than 10 characters.