List of lists into a Python Rich table

5.1k views Asked by At

Given the below, how can i get the animal, age and gender into each of the table cells please? Currently all the data ends up in one cell. Thanks

from rich.console import Console
from rich.table import Table

list = [['Cat', '7', 'Female'],
        ['Dog', '0.5', 'Male'],
        ['Guinea Pig', '5', 'Male']]

table1 = Table(show_header=True, header_style='bold')
table1.add_column('Animal')
table1.add_column('Age')
table1.add_column('Gender')

for row in zip(*list):
    table1.add_row(' '.join(row))

console.print(table1)
1

There are 1 answers

1
PIG208 On BEST ANSWER

Just use * to unpack the tuple and it should work fine.

for row in zip(*list):
    table1.add_row(*row)

Note that

table1.add_row(*('Cat', 'Dog', 'Guinea Pig'))

is equivalent to

table1.add_row('Cat', 'Dog', 'Guinea Pig')

While previously your approach was equivalent to

table1.add_row('Cat Dog Guinea Pig')