Forums

How to get api data into loop?

I have this code, to print out a league table of football teams:

 x30 = d30['table'][0]
    y30 = x30
    z30 = y30['name']

    x31 = d30['table'][1]
    y31 = x31
    z31 = y31['name']

    x32 = d30['table'][2]
    y32 = x32
    z32 = y32['name']

    x33 = d30['table'][3]
    y33 = x33
    z33 = y33['name']

    return render_template('sport.html',  z30=z30, z31=z31, etc....)

trying to make a loop so that I can print out all 24 teams in one go, without having to manually add each one every time

can't quite get it working, any one good at this stuff?

something like this for example:

 for x in range(0,24):
                x30 = d30['table'][x]
                y31 = x31
                z31 = y31['name']

             return z31

no worries, I've more or less sorted it now:

x = 0
            while x < 24:
                x30 = d30['table'][x]
                y30 = x30
                z30 = y30['name']
                print(z30)
                x = x+1

            return z30

only prob now is that it prints out the last team twice - how to get rid of that? thanks

and I guess this now has to be put into some kind of loop in the jinja template - that's where I'm struggling

any help would be great......

Not much experience in this, but tidy up your code like this:

for x in range(24):
   x30 = d30['table'][x]
   y30 = x30
   z30 = y30['name']
   print(z30)

Then at least it is more readable.

Here you go @MadMartin: https://jinja.palletsprojects.com/en/2.11.x/templates/#for

most docs, help sites seem to point to this kind of format:

{% for key, value in d30.items() %}
    <dt>{{ key|e }}</dt>
    <dd>{{ value|e }}</dd>
{% endfor %}
</dl>
</div>

however, this just gives the whole dictionary, rather than breaking the tuple down as shown below

x = 0
            while x < 24:
                x30 = d30['table'][x]
                y30 = x30
                z30 = y30['name']
                print(z30)
                x = x+1

I need to merge the two somehow

I mean, I need 'z30' to print out a nice column of teams

this seems to do the trick now:

 g = []
        x = 0
        while x < 24:
            x30 = d30['table'][x]
            y30 = x30
            z30 = y30['name']
            g.append(z30)
            x = x+1
            g2 = g
            g3 = str(g2)



        return render_template('sport7.html', g3=g3)

just need tidy the output a little, needs to go horizantal lettering

https://madmartin.pythonanywhere.com/cov2