Is there any way to print the python dictionary in to a table in HTML. I have a python dictionary and am sending to HTML by using
return render_template('index.html',result=result)
Now I need to print the elements in result dictionary in to HTML as a table.
Flask uses Jinja as the templating framework. You can just do the following in your template (html)
Jinja can also be used on its own as a mark-up renderer.
Python3 / Jinja2
<table>
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for key, value in result.items() %}
<tr>
<td> {{ key }} </td>
<td> {{ value }} </td>
</tr>
{% endfor %}
</tbody>
</table>
Python2 / Jinja
<table>
{% for key, value in result.iteritems() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
Check Flask-Table.
Example from the docs (slightly edited):
from flask_table import Table, Col
# Declare your table
class ItemTable(Table):
name = Col('Name')
description = Col('Description')
items = [dict(name='Name1', description='Description1'),
dict(name='Name2', description='Description2'),
dict(name='Name3', description='Description3')]
# Populate the table
table = ItemTable(items)
# Print the html
print(table.__html__())
# or just {{ table }} from within a Jinja template
I've had better luck putting the dictionary into a list of lists, then have the html loop through the list and print the table. The python would be:
Table = []
for key, value in results_dict.iteritems(): # or .items() in Python 3
temp = []
temp.extend([key,value]) #Note that this will change depending on the structure of your dictionary
Table.append(temp)
Then in your html you loop through the table.
<table>
{% for t in table %}
<tr>
{% for i in t %}
<td>{{ i }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With