Search code examples
pythonhtmlpython-3.xnested-lists

Transform a python nested list into an HTML table


I want to transform a list of rows in Python into an HTML table to ultimately send in an email body. Let's say my list of rows is stored as the variable req_list (representing the import data from a .csv file, for example) looks like:

> [['Email', 'Name', 'Name ID', 'Policy ID',
> 'Policy Number', 'Policy Effective Date'],
>  ['me@gmail.com','My Name', 
  '5700023153486', '57000255465455','C4545647216', '1/1/2017']]

Please ignore the above > formatting that appears incorrect.

You can probably guess that the first row in the list contains column headers. I want to generate an HTML table out of this list. Assume for this example that there could be any number of additional rows to add to the table, but no need to teach me about looping to handle this or error handling if there are 0.

How can I change this into an HTML table formatted relatively well? (e.g. black and white, with gridlines perhaps). I do not know HTML very well and have tried the following:

for thing in req_list:
    for cell in thing:
        req_tbl = req_tbl + "<tr><td>" + str(cell)

Which yields basically each "cell" in the list printed one after another on a single line, when read in my email inbox (the code sends this req_table variable to myself in an email)

Email
Name
Name ID
Policy ID

and so on.

How can I get this formatted into a proper HTML table? Furthermore, is there a way I can read the "html" text contained in req_table within python so I can check my work? I have used urllib to open pages/files but can't seem to pass it a variable.


Solution

  • You can use Pandas for that, only two lines of code:

    import pandas as pd
    
    df = pd.DataFrame(req_list[1:], columns=req_list[0])
    df.to_html()
    
    '<table border="1" class="dataframe">\n  <thead>\n    <tr style="text-align: right;">\n      <th></th>\n      <th>Email</th>\n      <th>Name</th>\n      <th>Name ID</th>\n      <th>Policy ID</th>\n      <th>Policy Number</th>\n      <th>Policy Effective Date</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>me@gmail.com</td>\n      <td>My Name</td>\n      <td>5700023153486</td>\n      <td>57000255465455</td>\n      <td>C4545647216</td>\n      <td>1/1/2017</td>\n    </tr>\n  </tbody>\n</table>'
    

    You can also read a html table into a DataFrame using:

    df = pd.read_html(req_table)