Applying the Table Printing Function to Various Data Structures
Now that we have our reusable table printing function, let's explore how to apply it to different data structures commonly used in Python.
Printing a Table from a List of Dictionaries
Suppose we have a list of dictionaries representing employee data:
employees = [
{'name': 'John Doe', 'age': 35, 'department': 'Sales'},
{'name': 'Jane Smith', 'age': 28, 'department': 'Marketing'},
{'name': 'Bob Johnson', 'age': 42, 'department': 'IT'},
{'name': 'Sarah Lee', 'age': 31, 'department': 'HR'}
]
We can use the print_table()
function to display this data in a table format:
print_table(employees, headers=['Name', 'Age', 'Department'])
This will output:
Name | Age | Department
--------------+-----+------------
John Doe | 35 | Sales
Jane Smith | 28 | Marketing
Bob Johnson | 42 | IT
Sarah Lee | 31 | HR
Printing a Table from a List of Lists
If your data is in the form of a list of lists, you can also use the print_table()
function:
data = [
['Apple', 10, 5.99],
['Banana', 15, 2.49],
['Orange', 8, 3.79],
['Kiwi', 12, 4.25]
]
headers = ['Fruit', 'Quantity', 'Price']
print_table(data, headers, align='right', padding=2)
This will output:
Fruit | Quantity | Price
----------+------------+----------
Apple | 10 | 5.99
Banana | 15 | 2.49
Orange | 8 | 3.79
Kiwi | 12 | 4.25
Printing a Table from a Pandas DataFrame
If you're working with data stored in a Pandas DataFrame, you can easily convert it to a list of dictionaries and then use the print_table()
function:
import pandas as pd
df = pd.DataFrame({
'Name': ['John Doe', 'Jane Smith', 'Bob Johnson', 'Sarah Lee'],
'Age': [35, 28, 42, 31],
'Department': ['Sales', 'Marketing', 'IT', 'HR']
})
print_table(df.to_dict('records'), headers=df.columns)
This will output:
Name | Age | Department
--------------+-----+------------
John Doe | 35 | Sales
Jane Smith | 28 | Marketing
Bob Johnson | 42 | IT
Sarah Lee | 31 | HR
By using the print_table()
function, you can easily display your data in a tabular format, regardless of the underlying data structure. This makes it a versatile and reusable tool for presenting information in your Python applications.