I have a dict
containing lists of strings and was wanting to print everything out as a table in the terminal in a format something like:
+----------------------------------------------+
| key1 | key2 | key3 | key4 |
+----------------------------------------------+
| val_1 | val_1 | val_1 | val_1 |
|----------|----------|-----------|------------|
| val_2 | val_2 | val_2 | val_2 |
+----------------------------------------------+
etc.
Is there an amazing module or a simple way of achieving this? I have a list of the column widths which I get by finding the longest val in each list.
You could use PrettyTable
.
apt-get install python-prettytable
..
#! /usr/bin/env python
from prettytable import PrettyTable
d1 = {
"key1":["val1_1", "val1_2"],
"key2":["val2_1", "val2_2"],
"key3":["val3_1", "val3_2"],
"key4":["val4_1", "val4_2"],
}
table = PrettyTable()
for key,val in sorted(d1.iteritems()):
table.add_column(key, sorted(val))
print table
The result is:
$ ./t
+--------+--------+--------+--------+
| key1 | key2 | key3 | key4 |
+--------+--------+--------+--------+
| val1_1 | val2_1 | val3_1 | val4_1 |
| val1_2 | val2_2 | val3_2 | val4_2 |
+--------+--------+--------+--------+
PrettyTable also provides HTML formatting. Replace the print table
with:
print table.get_html_string(attributes={"size":"100%", "class":"MyTable"})
and you get:
<table border="1" class="MyTable" size="100%">
<tr>
<th>key1</th>
<th>key2</th>
<th>key3</th>
<th>key4</th>
</tr>
<tr>
<td>val1_1</td>
<td>val2_1</td>
<td>val3_1</td>
<td>val4_1</td>
</tr>
<tr>
<td>val1_2</td>
<td>val2_2</td>
<td>val3_2</td>
<td>val4_2</td>
</tr>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With