1

I am able to create a python PrettyTable with a title and table fields. But, I want to create multiple sections in a single table i.e have multiple header (or html rowspan/ colspan to merge cells inorder to create sections). Any pointers for that?

Currently, I am able to create a table using:

table_fields = ['No','Name', 'Age']
from prettytable import PrettyTable
pt = PrettyTable(table_fields)
pt.padding_width = 1
pt.title = 'Customer Info'
pt.add_row(['1','abc','26'])
pt.add_row(['2','xyz','52'])

Output:

+------------------------------+
|    Customer Info             |
+------------------------------+ 
| No | Name      |    Age      |
+------------------------------+
| 1  |  abc      |   26        |
| 2  |  xyz      |   52        |
+------------------------------+

Desired Output:

+------------------------------+
|    Customer Info             |
+------------------------------+ 
| No | Name      |    Age      |
+------------------------------+
|  DEPARTMENT 1                |
+------------------------------+
| 1  |  abc      |   26        |
| 2  |  xyz      |   52        |
+------------------------------+
|  DEPARTMENT 2                |
+------------------------------+
| 1  |  pqr      |   44        |
| 2  |  def      |   31        |
+------------------------------+

Looking for a way to add Department 1 and Department 2 rows in the table.

iDev
  • 2,163
  • 10
  • 39
  • 64

1 Answers1

0

Here's as close as I've been able to get to the desired output (using a row for department number each time a new department's people are added to the table): NOTE: I was not able to find a way to change the column span of a cell, so I had to add blanks to fill up the expected number of cells or the row cannot be added.

+---------------------------+
|       Customer Info       |
+--------------+------+-----+
|      No      | Name | Age |
+--------------+------+-----+
| DEPARTMENT 1 |      |     |
|      1       | abc  |  41 |
|      2       | def  |  29 |
| DEPARTMENT 2 |      |     |
|      1       | pqr  |  21 |
|      2       | xyz  |  37 |
+--------------+------+-----+

With the following code:

from prettytable import PrettyTable

departments = {
    "1": {
        "abc": {
            "age": 41
        },
        "def": {
            "age": 29
        }
    },
    "2": {
        "pqr": {
            "age": 21
        },
        "xyz": {
            "age": 37
        }
    }
}

table_fields = ['No', 'Name', 'Age']
pt = PrettyTable(table_fields)
pt.padding_width = 1
pt.title = 'Customer Info'
person_no = 1
for department, people in departments.items():
    pt.add_row(["DEPARTMENT {}".format(department), "", ""])
    for name, person in people.items():
        pt.add_row([person_no, name, person["age"]])
        person_no += 1
    person_no = 1
print(pt)

I hope this is enough to meet your needs, and if you or anyone else knows how to specify column span for a cell, I would love to know!

Phil S
  • 95
  • 1
  • 6