Python Tabulate Module: Create and Manipulate ASCII Tables
The tabulate
module in Python allows you to create simple ASCII tables from lists or dictionaries of data.
It allows you to display data in a readable format in the console.
Basic Table Creation
You can use tabulate
to turn lists of lists or dictionaries into formatted tables.
from tabulate import tabulate # List of lists data = [ ["Ahmed", 28, "Engineer"], ["Fatima", 32, "Doctor"], ["Hassan", 24, "Teacher"] ] print(tabulate(data))
Output:
------- -- -------- Ahmed 28 Engineer Fatima 32 Doctor Hassan 24 Teacher ------- -- --------
You can also create tables from a list of dictionaries.
from tabulate import tabulate data = [ {"Name": "Salma", "Age": 27, "Occupation": "Architect"}, {"Name": "Kareem", "Age": 30, "Occupation": "Lawyer"}, {"Name": "Nadia", "Age": 22, "Occupation": "Designer"} ] print(tabulate(data, headers="keys"))
Output:
Name Age Occupation ------- ---- ----------- Salma 27 Architect Kareem 30 Lawyer Nadia 22 Designer
Here, the headers="keys"
argument tells tabulate
to use the dictionary keys as headers.
Row Manipulation
Add rows to existing tables
You can add new rows to your table data.
from tabulate import tabulate data = [ ["Heba", "HR"], ["Ayman", "IT"] ] # Adding a new row data.append(["Nada", "Finance"]) print(tabulate(data, headers=["Name", "Department"]))
Output:
Name Department ------ ----------- Heba HR Ayman IT Nada Finance
After appending [“Nada”, “Finance”] to data
, the new row appears in the table.
Insert rows at specific positions
You can insert a row at a specific index.
from tabulate import tabulate data = [ ["Samir", "Logistics"], ["Nour", "Operations"] ] # Inserting a row at position 1 data.insert(1, ["Leila", "Procurement"]) print(tabulate(data, headers=["Name", "Department"]))
Output:
Name Department ------ ----------- Samir Logistics Leila Procurement Nour Operations
Leila’s data is inserted between Samir and Nour.
Remove rows
You can remove rows from your table.
from tabulate import tabulate data = [ ["Adel", "Sales"], ["Sara", "Customer Service"], ["Hadi", "Support"] ] # Removing the second row del data[1] print(tabulate(data, headers=["Name", "Department"]))
Output:
Name Department ------ ----------- Adel Sales Hadi Support
After deleting the second row, Sara’s data is removed from the table.
Column Manipulation
Add columns to existing tables
You can add a new column to your table data.
from tabulate import tabulate data = [ ["Farah", "Engineering"], ["Youssef", "Design"] ] # Adding a new column for row in data: row.append("Active") print(tabulate(data, headers=["Name", "Department", "Status"]))
Output:
Name Department Status -------- ------------ -------- Farah Engineering Active Youssef Design Active
By appending “Active” to each row, a new column “Status” is added.
Reorder columns
You can change the order of columns in your table.
from tabulate import tabulate data = [ ["Layla", 85, 90], ["Omar", 78, 88] ] # Reordering columns data_reordered = [[row[2], row[0], row[1]] for row in data] print(tabulate(data_reordered, headers=["Science", "Name", "Math"]))
Output:
Science Name Math ------- ------ ----- 90 Layla 85 88 Omar 78
Columns are reordered to display “Science” scores first.
Hide specific columns
You can exclude columns from your table.
from tabulate import tabulate data = [ ["Karim", "Admin", "Full-time"], ["Hana", "HR", "Part-time"] ] # Excluding the "Status" column data_modified = [[row[0], row[1]] for row in data] print(tabulate(data_modified, headers=["Name", "Department"]))
Output:
Name Department ------ ----------- Karim Admin Hana HR
By not including the “Status” data, the “Status” column is hidden.
Show Index
You can display row indices in your table.
from tabulate import tabulate data = [ ["Mohamed", "Manager"], ["Aya", "Supervisor"] ] print(tabulate(data, headers=["Name", "Position"], showindex=True))
Output:
Name Position -- ------- ---------- 0 Mohamed Manager 1 Aya Supervisor
You can add a caption or footnote below your table.
from tabulate import tabulate data = [ ["Samia", "Paid"], ["Khaled", "Pending"] ] table = tabulate(data, headers=["Customer", "Payment Status"], tablefmt="plain") caption = "Note: Payment status as of September." print(f"{table}\n\n{caption}")
Output:
Customer Payment Status Samia Paid Khaled Pending Note: Payment status as of September.
Nested Tabes
To create a nested table using the tabulate
, you can structure your data as a list of lists, where each sublist represents a row in the table.
from tabulate import tabulate # Sample data with a 4x4 inner table data = [ ["Mohamed", "Engineering", [ ["Task 1", "Task 2", "Task 3", "Task 4"], ["Done", "In Progress", "Pending", "Done"], ["High", "Medium", "Low", "High"], ["2024-01-01", "2024-02-01", "2024-03-01", "2024-04-01"] ]], ["Ahmed", "Marketing", [ ["Task A", "Task B", "Task C", "Task D"], ["Launched", "Planning", "Pending", "Launched"], ["Medium", "High", "Low", "Medium"], ["2024-01-15", "2024-02-15", "2024-03-15", "2024-04-15"] ]], ["Khaled", "HR", [ ["Task X", "Task Y", "Task Z", "Task W"], ["Ongoing", "Scheduled", "Pending", "Completed"], ["Low", "Medium", "High", "Low"], ["2024-01-10", "2024-02-10", "2024-03-10", "2024-04-10"] ]] ] # Function to format the 4x4 inner table with borders def format_inner_table(inner_table): return tabulate(inner_table, tablefmt="grid") # Prepare data for tabulation formatted_data = [ [name, department, format_inner_table(inner_table)] for name, department, inner_table in data ] headers = ["Name", "Department", "Details"] table = tabulate(formatted_data, headers=headers, tablefmt="grid") print(table)
Output:
+---------+--------------+--------------------------------------------------------+ | Name | Department | Details | +=========+==============+========================================================+ | Mohamed | Engineering | +------------+-------------+------------+------------+ | | | | | Task 1 | Task 2 | Task 3 | Task 4 | | | | | +------------+-------------+------------+------------+ | | | | | Done | In Progress | Pending | Done | | | | | +------------+-------------+------------+------------+ | | | | | High | Medium | Low | High | | | | | +------------+-------------+------------+------------+ | | | | | 2024-01-01 | 2024-02-01 | 2024-03-01 | 2024-04-01 | | | | | +------------+-------------+------------+------------+ | +---------+--------------+--------------------------------------------------------+ | Ahmed | Marketing | +------------+------------+------------+------------+ | | | | | Task A | Task B | Task C | Task D | | | | | +------------+------------+------------+------------+ | | | | | Launched | Planning | Pending | Launched | | | | | +------------+------------+------------+------------+ | | | | | Medium | High | Low | Medium | | | | | +------------+------------+------------+------------+ | | | | | 2024-01-15 | 2024-02-15 | 2024-03-15 | 2024-04-15 | | | | | +------------+------------+------------+------------+ | +---------+--------------+--------------------------------------------------------+ | Khaled | HR | +------------+------------+------------+------------+ | | | | | Task X | Task Y | Task Z | Task W | | | | | +------------+------------+------------+------------+ | | | | | Ongoing | Scheduled | Pending | Completed | | | | | +------------+------------+------------+------------+ | | | | | Low | Medium | High | Low | | | | | +------------+------------+------------+------------+ | | | | | 2024-01-10 | 2024-02-10 | 2024-03-10 | 2024-04-10 | | | | | +------------+------------+------------+------------+ | +---------+--------------+--------------------------------------------------------+
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.