Skip to content

Python tabulate dictionary | Example code

  • by

Using the Tabulate package to tabulate a dictionary will print in tabular format.

tabulate (
tabular_data,
headers: tuple=tuple,
tablefmt: str=str,
floatfmt: str=str,
numalign: =decimal,
stralign: str=str,
missingval: str=str,
showindex: str=str,
disable_numparse: bool=False,
colalign: __class__=None
)

Python tabulate dictionary example

Simple example code Printing dict as tabular Data. Headers can be an explicit list of column headers if headers=”firstrow”, then the first row of data is used if headers=”keys”, then dictionary keys or column indices are used.

If tabulate package is not installed then first install it and import the module.

from tabulate import tabulate

dict1 = [["#", "Gender", "age"], ["Alice", "F", 24], ["Bob", "M", 19]]

print(tabulate(dict1, headers="firstrow"))

Output:

Python tabulate dictionary

Python Tabulate Dictionary containing two values per key

from tabulate import tabulate

d = {"Dave": ("13", "Male"), "Sarah": ("16", "Female")}

headers = ["Name", "Age", "Gender"]
print(tabulate([(k,) + v for k, v in d.items()], headers=headers))

Output:

Name      Age  Gender
------  -----  --------
Dave       13  Male
Sarah      16  Female

Printing dict as tabular Data

Convert the dict to a dataframe.

from decimal import Decimal

import pandas as pd
from tabulate import tabulate

board_dict = {
    'Done': {
        'point': 0.0,
        'items': 1
    },
    'Doing': {
        'point': 24.0,
        'items': 3
    },
    'New': {
        'point': 0.0,
        'items': 2
    },
    'Stuck': {
        'point': 19.0,
        'items': 3
    },
    'Ready to Test': {
        'point': Decimal('1'),
        'items': 1
    }
}

df = pd.DataFrame(board_dict)
print(tabulate(df.T, headers="keys"))

Output:

                 point    items
-------------  -------  -------
Done                 0        1
Doing               24        3
New                  0        2
Stuck               19        3
Ready to Test        1        1

Do comment if you have any doubts or suggestions on this Python tabulate topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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