29

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
just_in
  • 437
  • 3
  • 6
  • 10

7 Answers7

52

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>
Konchog
  • 1,920
  • 19
  • 23
codegeek
  • 32,236
  • 12
  • 63
  • 63
6

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
Parzival
  • 2,004
  • 4
  • 33
  • 47
5

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>
TrebledJ
  • 8,713
  • 7
  • 26
  • 48
Jroosterman
  • 408
  • 4
  • 11
  • i need to make only certain cells in the table to be editable. And also i would like to add 'datetimepicker.js' module on some cells. Is ther any way? – just_in Feb 19 '13 at 20:07
  • So you make the editable cells in the table a text box with the default value of whatever is in the dictionary. You could give the textbox an unique id so datetimepicker could get the cell you want to change. – Jroosterman Feb 20 '13 at 14:15
4

so I wanted an easy way to generate html from python dictionary with only inline styles (because emails) and couldn't find anything that I was satasfied with so I wrote this,

it's very simple to use and easy to add styles to

<table style="margin: 3px">
    <tr style="background-color: #7cc3a97d">
        <th style="color: white">col1</th>
        <th style="color: white">col2</th>
        <th style="color: white">col3</th>
        <th style="color: white">col4</th>
    </tr>

    <tr style="background-color: aliceblue">
        <td style="padding: 1rem">value11</td>
        <td style="padding: 1rem">value21</td>
        <td style="padding: 1rem">value31</td>
        <td style="padding: 1rem">value41</td>
    </tr>
    <tr style="background-color: #c2d4e4">
        <td style="padding: 1rem">value12</td>
        <td style="padding: 1rem">value22</td>
        <td style="padding: 1rem">value32</td>
        <td style="padding: 1rem">value42</td>
    </tr>
    <tr style="background-color: aliceblue">
        <td style="padding: 1rem">value13</td>
        <td style="padding: 1rem">value23</td>
        <td style="padding: 1rem">value33</td>
        <td style="padding: 1rem">value43</td>
    </tr>
</table>

lets say you have the following dictionary

myDict = {
    'col1' : ['value11', 'value12', 'value13'],
    'col2' : ['value21', 'value22', 'value23'],
    'col3' : ['value31', 'value32', 'value33'],
    'col4' : ['value41', 'value42', 'value43'],
}

it can be converted with

class HTML:

    def __init__(self, Header, tableStyles = {}, trStyles = {}, thStyles = {}):
        self.tableStyles = HTML._styleConverter(tableStyles)
        trStyles = HTML._styleConverter(trStyles)
        thStyles = HTML._styleConverter(thStyles)
        self.rows = []
        self.Header= f'<tr {trStyles} >'
        for th in Header:
            self.Header += f'\n<th {thStyles} >{th}</th>'
        self.Header += '\n</tr>'

    @staticmethod
    def _styleConverter(styleDict : dict):
        if styleDict == {}:
            return ''
        styles = ''
        for [style, value] in styleDict.items():
            styles +=f'{style}: {value};'
        return f'style="{styles}"'

    def addRow(self, row, trStyles = {}, tdStyles = {}):
        trStyles = HTML._styleConverter(trStyles)
        tdStyles = HTML._styleConverter(tdStyles)
        temp_row = f'\n<tr {trStyles} >'
        for td in row:
            temp_row += f'\n<td {tdStyles} >{td}</td>'
        temp_row += '\n</tr>'
        self.rows.append(temp_row)


    def __str__(self):


        return \
f'''
<table {self.tableStyles} >
{self.Header}
{''.join(self.rows)}
</table>
'''



def dictionaryToHTMLTable(dict : dict):
    html = HTML(Header = dict.keys(),
                tableStyles={'margin': '3px'},
                trStyles={'background-color': '#7cc3a97d'},
                thStyles={ 'color': 'white'})
    for i, row in enumerate(zip(*dict.values())):
        print(row)
        if i%2 == 0:
            BGC = 'aliceblue'
        else:
            BGC = '#c2d4e4'
        html.addRow(row, trStyles={'background-color' : BGC}, tdStyles={'padding': '1rem'})
    return html

and to output

print(dictionaryToHTMLTable(myDict))

coder
  • 700
  • 8
  • 12
  • Thank you so much, what happens if the dict values lengths are not equal for example {"no_login": ["abc","bcd","cfg"], "no_report": ["1","2","3"], "no_link": ["hello","hii"]} – Prarthan Ramesh Mar 31 '22 at 09:18
  • @PrarthanRamesh I've ran your example and it works well, you just might want to add some styles inside the function `dictionaryToHTMLTable` to center the text – coder Mar 31 '22 at 17:41
  • thanks, i made some code change to make all the list length are same so that table cell are not showing bit off – Prarthan Ramesh Apr 01 '22 at 08:13
2

For python3, no () after result.items

<table>
{% for key, value in result.items %}
   <tr>
        <th> {{ key }} </th>
        <td> {{ value }} </td>
   </tr>
{% endfor %}
</table>
Ying Wang
  • 47
  • 5
1

Iterate through the dictionary items using result.iteritems() and then write the keys/data into rows of an html table.

1
#!/usr/bin/env python3

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.items()))


if __name__ == "__main__":
    d = {key: value for value, key in enumerate("abcdefg")}
    print(d)
    print(dict_to_html_table(d))

cclauss
  • 552
  • 6
  • 17