Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary in to html table

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.

like image 346
just_in Avatar asked Feb 01 '13 18:02

just_in


3 Answers

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>
like image 64
codegeek Avatar answered Nov 20 '22 12:11

codegeek


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
like image 34
Parzival Avatar answered Nov 20 '22 13:11

Parzival


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>
like image 5
Jroosterman Avatar answered Nov 20 '22 13:11

Jroosterman