Skip to content Skip to sidebar Skip to footer

Python Prettytable With Multiple Header/ Title

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

Solution 1:

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 = 1for 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 = 1print(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!

Post a Comment for "Python Prettytable With Multiple Header/ Title"