Skip to content

Python print dictionary as table | Example code

  • by

Use for loop with the format to print dictionary as a table in Python. Or you can use zip format for the same.

Example print a dictionary as table in Python

Simple example code.

Using for loop with formate {}

dict1 = {1: ["John", 21, 'CS'],
         2: ["Tim", 20, 'EE'],
         3: ["Steve", 21, 'Civil'],

# Print the names of the columns.
print("{:<10} {:<10} {:<10}".format('NAME', 'AGE', 'COURSE'))

# print each data item.
for key, value in dict1.items():
    name, age, course = value
    print("{:<10} {:<10} {:<10}".format(name, age, course))


Python print dictionary as table

Using zip() function

The input dictionary formate has changed for this example.

dict1 = {'NAME': ['John', 'Tim', 'Steve'],
         'AGE': [21, 20, 21],
         'COURSE': ['Data Structures', 'Machine Learning', 'OOPS with Java']}

for each_row in zip(*([i] + (j)
                      for i, j in dict1.items())):
    print(*each_row, " ")


John 21 Data Structures
Tim 20 Machine Learning
Steve 21 OOPS with Java

OR you can use the tabulate library. If you don’t have it installed, you can install it using pip:

pip install tabulate

Here’s an example of how to print a dictionary as a table:

from tabulate import tabulate

# Sample dictionary
data = {
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [25, 30, 22],
    "City": ["New York", "Los Angeles", "Chicago"]

# Convert the dictionary to a list of lists (table format)
table_data = []
for key, values in data.items():
    table_data.append([key] + values)

# Print the table
print(tabulate(table_data, headers="firstrow", tablefmt="grid"))

Comment if you have any doubts or suggestions on this Python print dictionary 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 *