Bruce
Bruce

Reputation: 103

How to iterate through a dictionary in a dictionary in django template using django template tag?

My dictionary looks like this:

a = {
            "1": {
                "league_id": "1",
                "name": "2018 Russia World Cup",
                "country": "World",
                "country_code": "",
                "season": "2018",
                "season_start": "2018-06-14",
                "season_end": "2018-07-15",
                "standings": False,
            },
            "2": {
                "league_id": "2",
                "name": "Premier League",
                "country": "England",
                "country_code": "GB",
                "season": "2018",
                "season_start": "2018-08-10",
                "season_end": "2019-05-12",
                "standings": True
            },
        }

I want to loop through the dict and display all values for "name" and "country".

my code in my .html template looks like:

          {% for c in a %}
                 <thead>{{ a[c]['country'] }}</thead>
          {% endfor %}

          {% for n in a %} 
            <tr>
                <td>{{  a[n]['name'] }}</td>
            </tr>
          {% endfor %}

This gave an error:

Could not parse the remainder: '[c]['country']' from 'leagues[c]['country']'

I also tried

     {% for c in leagues %}
            <thead>{{ leagues.c.country }}</thead>
     {% endfor %}

     {% for n in leagues %}
            <tr>
                <td>{{  a.n.name }}</td>
            </tr>
    {% endfor %}

It gave a blank page.

How do I target the values name and country?

Upvotes: 0

Views: 90

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600059

You are not using Jinja, you are using Django template language.

But this is not how you loop through dicts or lists in Python. When you do for x in whatever, x is the actual element, not the index. Also, when you want to loop through the values of a dict, you need to use the values method.

 {% for league in leagues.values %}
        <thead>{{ league.country }}</thead>
 {% endfor %}

 {% for league in leagues.values %}
        <tr>
            <td>{{ league.name }}</td>
        </tr>
{% endfor %}

Upvotes: 1

Related Questions