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(\'i
For python3, no () after result.items
<table>
{% for key, value in result.items %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
Flask uses Jinja as the templating framework. You can just do the following in your template (html)
<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
tbl_fmt = '''
<table> {}
</table>'''
row_fmt = '''
<tr>
<td>{}</td>
<td>{}</td>
</tr>'''
def dict_to_html_table(in_dict):
return tbl_fmt.format(''.join([row_fmt.format(k,v) for k,v in in_dict.iteritems()]))
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>
Iterate through the dictionary items using result.iteritems()
and then write the keys/data into rows of an html table.