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
Asked
Active
Viewed 2,390 times
1

Ajay Krishnan
- 11
- 2
1 Answers
2
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.

Panda142308
- 27
- 13
-
This doesn't seem to be accurate any more. Maybe I'm overlooking it, but I don't see this in the prettytable documentation, or the prettytable code. – the1gofer Mar 27 '22 at 15:41
-
You may be right. At the time of writing this, I was using Python2.7 and prettytable v0.7.2. – Panda142308 Mar 30 '22 at 06:33