6

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)
yeleek
  • 199
  • 3
  • 15

1 Answers1

7

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')
PIG208
  • 2,060
  • 2
  • 10
  • 25
  • very helpful. also, in some cases, you may need to map elements with str, like *table.add_row(*(map(str, imd_table[index])))* – rjha94 Mar 11 '23 at 07:58