Home > other >  Django Template with a Dicitonary of Lists
Django Template with a Dicitonary of Lists

Time:06-15

Using django I am passing a dictionary of lists as the context for my template. The dictionary is structured as such:

weather = {
        'temp' : temp,
        'time' : time,
        'pop' : pop
    }

Temp, time, and pop are lists of equal length with each index of those lists going together. Meaning temp[1] , time[1], and pop[1] are together and temp[2] , time[2], and pop[3] and so on.

I would like to display these values like so:

temp[1]
time[1]
pop[1]
temp[2]
time[2]
pop[2]
.
.
.
temp[y]
time[y]
pop[y] #y is the length of the lists

I have tried to do this by making a for loop in my template the looks like this:

{%for x in weather%}
   <p>
      <span>{{weather.temp.x}}</span>
      <br>
      <span>{{weather.pop.x}}</span>
      <br>
      <span>{{weather.time.x}}</span>
      <br>
   </p>
{%endfor%}

But all this does is make empty lines. Could I get some help please?

CodePudding user response:

For x in weather will just loop through the lists and end after the third list, so I suspect you need a different approach, as you will need to collect the data in appropriate groups and templates aren't suited for such actual work.

Assuming three lists, all of the same length, you can zip them into parallel lists

views.py

temp = [1,2,3]
time = [4,5,6]
pop =  [7,8,9]

weather=zip(temp,time, pop)

And then in your template, output them in a readable fashion

{% for temp, time, pop in weather %}
    {{temp}}<br> 
    {{time}}<br>
    {{pop}}<br>
{% endfor %}

This should give you the output:

1
4
7
2
5
8
3
6
9
  • Related