List of lists into a Python Rich table
Asked Answered
E

1

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)
Ehrenberg answered 9/12, 2020 at 12:32 Comment(3)
Where/what is the definition of a ?rich? Table? Is it an external package?Thrombosis
Sorry my mistake - missed the import.Ehrenberg
before printing table with console, you should define console as console = Console()Gravamen
I
8

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')
Indeliberate answered 9/12, 2020 at 12:45 Comment(1)
very helpful. also, in some cases, you may need to map elements with str, like table.add_row(*(map(str, imd_table[index])))Butterbur

© 2022 - 2024 — McMap. All rights reserved.