How to Sort Data Before Displaying with Tabulate in Python

Since tabulate doesn’t support sorting natively, you need to sort your data structures before displaying them.

This tutorial will guide you through sorting various data types before using Python tabulate.

 

 

Using sorted() Function

Sort a List of Lists

Suppose you have a list of lists containing employee data. You can sort this data before displaying it like this:

from tabulate import tabulate
employees = [
    ['Ahmed', 30, 'Engineering'],
    ['Fatma', 25, 'Marketing'],
    ['Omar', 35, 'Sales'],
    ['Nour', 28, 'Engineering']
]

# Sort employees by age
sorted_employees = sorted(employees, key=lambda x: x[1])
print(tabulate(sorted_employees, headers=['Name', 'Age', 'Department']))

Output:

Name      Age  Department
------  -----  ------------
Fatma      25  Marketing
Nour       28  Engineering
Ahmed      30  Engineering
Omar       35  Sales

In the output, the employees are sorted by age in ascending order.

Sort a List of Dictionaries

If your data is a list of dictionaries, you can also sort it using sorted():

from tabulate import tabulate
employees = [
    {'Name': 'Ahmed', 'Age': 30, 'Department': 'Engineering'},
    {'Name': 'Fatma', 'Age': 25, 'Department': 'Marketing'},
    {'Name': 'Omar', 'Age': 35, 'Department': 'Sales'},
    {'Name': 'Nour', 'Age': 28, 'Department': 'Engineering'}
]
sorted_employees = sorted(employees, key=lambda x: x['Name'])
print(tabulate(sorted_employees, headers='keys'))

Output:

Name      Age  Department
------  -----  ------------
Ahmed      30  Engineering
Fatma      25  Marketing
Nour       28  Engineering
Omar       35  Sales

Here, the data is sorted alphabetically by the employees’ names.

 

Using Pandas DataFrame

You can use pandas df.sort_values() to sort by multiple columns:

import pandas as pd
from tabulate import tabulate
data = {
    'Name': ['Ahmed', 'Fatma', 'Omar', 'Nour'],
    'Age': [30, 25, 35, 28],
    'Department': ['Engineering', 'Marketing', 'Sales', 'Engineering']
}
df = pd.DataFrame(data)

# Sort by Department, then by Age
df_sorted = df.sort_values(by=['Department', 'Age'])
print(tabulate(df_sorted, headers='keys', showindex=False))

Output:

Name      Age  Department
------  -----  ------------
Nour       28  Engineering
Ahmed      30  Engineering
Fatma      25  Marketing
Omar       35  Sales

The data is first sorted by the ‘Department’ column, and then by ‘Age’ within each department.

 

In-Place Sorting with .sort()

When working with lists, you can sort them in place using the .sort() method.

from tabulate import tabulate
ages = [30, 25, 35, 28]

# Sort the ages in descending order
ages.sort(reverse=True)
print(tabulate([[age] for age in ages], headers=['Age']))

Output:

  Age
-----
   35
   30
   28
   25

The list ages is sorted in place, and the ages are displayed in descending order.

Leave a Reply

Your email address will not be published. Required fields are marked *