laila
laila

Reputation: 1059

Flask and HTML, from python dictionary to HTML table iteratively

I have a python dictionary of the form

data = {
    'category1': {
        'titles': ['t1', 't2', 't3'],
        'dates': ['d1', 'd2', 'd3']
    },
    'category2': {
        'titles': ['t4', 't5', 't6'],
        'dates': ['d4', 'd5', 'd6']
    }
}

and I want to create an html table which looks like:

category1        category2
t1               t4
d1               d4
--------------------------
t2               t5
d2               d5
--------------------------
t3               t6
d3               d6
--------------------------

I am using flask, my flask/python code is:

from flask import Flask, render_template
import pickle

app = Flask(__name__)

@app.route('/')
def hello_world():
    data=pickle.load(open('results.p','rb'))

    return render_template('index.html', x=data)

if __name__ == "__main__":
    app.run()

and my HTML template is:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>My Webpage</title>

</head>

<body>

<table>
{% for r,s in x.iteritems() %}
    <tr>
      <td>{{ r['titles'] }}{{r['dates']}}</td>
      <td>{{ s['titles'] }} {{s['dates']}}</td>
    </tr>
{% endfor %}
</table>
</body>
</html>

However I am getting an internal server error when I run this.

I have also tired data.iteritems() without any joy.

I also followed the accepted answer here: Python dictionary in to html table, but I get the same error.

Upvotes: 0

Views: 3403

Answers (2)

poke
poke

Reputation: 387547

newdata = zip(
    zip(*(x['titles'] for x in data.values())),
    zip(*(x['dates'] for x in data.values())))

print(list(data.keys()))
for group in newdata:
    for row in group:
        print(row)
    print('-----')

Gives you this output:

['category1', 'category2']
('t1', 't4')
('d1', 'd4')
-----
('t2', 't5')
('d2', 'd5')
-----
('t3', 't6')
('d3', 'd6')
-----

As you can see, the items are now correctly paired in newdata. So now you can iterate over it better and produce your table output.

The template code could then look like this:

<table>
  {% for group in x %}
     {% for row in group %}
     <tr>
       <td>{{ row[0] }}</td>
       <td>{{ row[1] }}</td>
    </tr>
    {% endfor %}
  {% endfor %}
</table>

Upvotes: 1

Alireza Bashiri
Alireza Bashiri

Reputation: 452

Take a look, I hope that is useful :D

<!DOCTYPE html>
<html lang="en">
<head>
    <title>My Webpage</title>
</head>
<body>
    <table>
        {% for r in x.values() %}
            <tr>
              <td>{{ r['titles'] }}{{ r['dates'] }}</td>
            </tr>
        {% endfor %}
    </table>
</body>
</html>

Upvotes: 0

Related Questions