Ajay Krishnan
Ajay Krishnan

Reputation: 11

Setting column width for columns in prettytable

I have to print more than one table using prettytable and also the size each column should match with the size of corresponding column in other tables also. I didn't find any function where I can specify the width of each column. The column width is determined corresponding to the length of biggest string and those length are different in each table. How can I align the columns of each table with others

Upvotes: 1

Views: 3045

Answers (1)

Panda142308
Panda142308

Reputation: 27

You can specify per column width using _max_width. I have this table :

+-------+------+------------+
| index | type |    name    |
+----- -+------+------------+
|   1   |  1   | username_1 |
|   2   |  2   | username_2 |
+------ +------+------------+

After specifying widths for two of the columns, I get the output below

def print_dict_to_table(mydict):
    t = PrettyTable(mydict[0].__dict__.keys())
    t._max_width = {"name":3, "type":3}
    for i in range(0, len(mydict)):
        t.add_row(mydict[i].__dict__.values())
    print(t)


+-------+------+------+
| index | type | name |
+-------+------+------+
|   1   |  1   | user |
|       |      | name |
|       |      |  _1  |
|   2   |  2   | user |
|       |      | name |
|       |      |  _2  |
+-------+------+------+

You can create a dictionary for the column widths and reuse it in your tables. For any field not mentioned in _max_widths, it is aligned to the longest string in the column.

Upvotes: 2

Related Questions