Search code examples
pythoniterationnested-listslist-manipulation

How do I zip a list of lists into a Python Rich table with headers and rows


I'm trying to extract data from a Google Sheet of indefinite size and use it to build a table to display in the terminal, but I'm evidently doing something wrong. I'm trying out the method and syntax described in this post (List of lists into a Python Rich table) and getting the equivalent of:

Animal Age Gender
Cat Dog Guinea Pig
7 0.5 5
Female Male Male

Instead of the desired:

Animal Age Gender
Cat 7 Female
Dog 0.5 Male
Guinea Pig 5 Male

Could anyone clarify? Apologies if it's something silly; I'm quite new to Python as you can probably tell.

My actual code, in case you can spot the fault, is:

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

records = test_records.get_all_values()
table = Table(title="Test Records")

for heading in records[0]:
    table.add_column(f"{heading}")

for row in zip(*records[1::1]):
    table.add_row(*row)

console = Console()
console.print(table)

Like the OP in that question, I have a list of lists, stored as the variable records as referenced in the above code. My list contains my headers, but I'm handling those separately in the code above as you can see. Perhaps that's where I'm going wrong?

Example of list data:

 records = [
     ['Date', 'Time', 'Username', 'Value (A)', 'Value (B)', 'Message'],
     ['07.04.22', '09:00', 'John', '3.00', '3.00', 'Some string data.'],
     ['08.04.22', '10:00', 'Jane', '3.00', '5.00', 'Some string data.']
 ]

Solution

  • I'm pretty sure that the zip function isn't needed. Remove it and it works.

    from rich.console import Console
    from rich.table import Table
    
    records = test_records.get_all_values()
    table = Table(title="Test Records")
    
    for heading in records[0]:
        table.add_column(f"{heading}")
    
    for row in records[1::1]:
        table.add_row(*row)
    
    console = Console()
    console.print(table)
    

    Your data is already formatted in a horizontal way, not vertical.