Search code examples
pythonhtml-tabletablecolumn

Creating a HTML table with Python with multiple columns for a specific row


I wrote this code:

tr = ""
for author, projects in data.iteritems():
    tr + = "<tr><td>{}</td>".format(author)
    for project, branches in projects.iteritems():
        tr += "<td>{}</td>".format(project)
        for branch in branches:
            tr += "<td>{}</td>".format(branch)
    tr += </td></tr>
end = "</table>"

I have this dataset

{
'user_one': {'project_a': ['branch_1', 'branch_2'],
          'project_b': ['branch_1']},
'user_two': {'project_x': ['branch_x1', 'branch_b'] }
}

I want to print table like below:

+-------------------------------------------+
|    User    |    Project    |    Branch    |
+------------+---------------+--------------+
|  user_one  |   project_a   |   branch_1   |
+------------+---------------+--------------+
|            |               |   branch_2   |
+------------+---------------+--------------+
|            |   project_b   |   branch_1   |
+------------+---------------+--------------+
|  user_two  |  project_x    |   branch_x1  |
+------------+---------------+--------------+
|            |               |   branch_b   |
+------------+---------------+--------------+

if its single project it works fine but when it comes multiple projects, it doesn't. I can get the result using PrettyTable but I since I want project_a, _b , _x etc to be hyperlinks. I cannot achieve it in while using PrettyTable, so I started writing my own html generator based on data.


Solution

  • why depend on a whole package if your need is just rendering the table !

    table = "<table border=1 ><tr><th>user</th><th>Project</th><th>Branch</th></tr>"
    tr = ""
    td_1 = ""
    td_2 = ""
    for author, projects in data.iteritems():
        # reset the value for new input.
        td_1 = ""
        td_2 = ""
        for project, branches in projects.iteritems():
            td_1 += "{}<hr>".format(project)
            for branch in branches:
                td_2 += "{}<hr>".format(branch)
        tr += "<tr><td valign='top'>{}</td><td valign='top'>{}</td><td valign='top'>{}</td></tr>".format(author, td_1, td_2)
    
    end = "</table>"
    table = table + tr + end
    

    this renders

    enter image description here

    you can use css and customise the look .. I hope this helps !