Generating Random People Table with Rich Library

  • Share this:

Code introduction


This code defines a function that uses the Rich library to generate a table of a random list of people.


Technology Stack : The package and technology stack used by the code include Rich library, Table, and Console.

Code Type : The type of code

Code Difficulty : Intermediate


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

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

    for i in range(num_rows):
        name = f"Person {i+1}"
        age = random.randint(18, 70)
        city = random.choice(["New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia", "San Antonio", "San Diego", "Dallas", "San Jose"])
        table.add_row(name, str(age), city)

    console.print(table)