Generating Random Data Tables with Rich Library

  • Share this:

Code introduction


This function uses the Console and Table classes from the Rich library to generate a table with random data and print it to the console.


Technology Stack : Rich, Console, Table

Code Type : The type of code

Code Difficulty : Intermediate


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

def generate_random_table(num_rows):
    console = Console()
    table = Table(show_header=True, header_style="bold magenta")
    table.add_column("Name", style="green")
    table.add_column("Age", style="red")
    table.add_column("City", style="blue")

    for _ in range(num_rows):
        name = f"Person {_}"
        age = random.randint(18, 70)
        city = random.choice(["New York", "London", "Tokyo", "Berlin", "Paris"])
        table.add_row(name, str(age), city)

    console.print(table)