Python dictionary in to html table

后端 未结 7 1282
刺人心
刺人心 2020-12-23 21:33

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         


        
相关标签:
7条回答
  • 2020-12-23 21:57

    For python3, no () after result.items

    <table>
    {% for key, value in result.items %}
       <tr>
            <th> {{ key }} </th>
            <td> {{ value }} </td>
       </tr>
    {% endfor %}
    </table>
    
    0 讨论(0)
  • 2020-12-23 22:04

    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>
    
    0 讨论(0)
  • 2020-12-23 22:04

    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
    
    0 讨论(0)
  • 2020-12-23 22:05
    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()]))
    
    0 讨论(0)
  • 2020-12-23 22:16

    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>
    
    0 讨论(0)
  • 2020-12-23 22:17

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

    0 讨论(0)
提交回复
热议问题