Skip to content

Python print nested dictionary as table | Example code

  • by

Using the pandas module you can print a nested dictionary as a table in Python.

Example print nested dictionary as table in Python

Simple example code. The df.fillna(0) replaces missing values with 0.

import pandas as pd

data = {'bin1': {'A': 14545,
                 'B': 18579,
                 'C': 5880,
                 'D': 20771,
                 'E': 404396},
        'bin2': {'A': 13200,
                 'D': 16766,
                 'E': 200344},
        }

df = pd.DataFrame(data).T
df.fillna(0, inplace=True)
print(df)

Output:

Python print nested dictionary as table

Another example

You can use pandas.DataFrame.from_dict with orient=index.

import pandas as pd

student = {
    "student1": {
        "Name": "Eddy",
        "Grade": 1,
        "Math": 78,
        "English": 65,
        "Physics": 89,
        "Chemistry": 80
    },
    "student2": {
        "Name": "Jim",
        "Grade": 2,
        "Math": 89,
        "English": 65,
        "Physics": 87,
        "Chemistry": 76

    },
    "student3": {
        "Name": "Jane",
        "Grade": 3,
        "Math": 87,
        "English": 97,
        "Physics": 75,
        "Chemistry": 64

    },
}

df = pd.DataFrame.from_dict(student, orient='index').reset_index(drop=True)

print(df)

Output:

   Name  Grade  Math  English  Physics  Chemistry
0  Eddy      1    78       65       89         80
1   Jim      2    89       65       87         76
2  Jane      3    87       97       75         64

Source: stackoverflow.com

For a markdown table

Use pandas.DataFrame.to_markdown()

print(df.to_markdown(index=False))

Output:

| Name   |   Grade |   Math |   English |   Physics |   Chemistry |
|:-------|--------:|-------:|----------:|----------:|------------:|
| Eddy   |       1 |     78 |        65 |        89 |          80 |
| Jim    |       2 |     89 |        65 |        87 |          76 |
| Jane   |       3 |     87 |        97 |        75 |          64 |

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

Note: IDE: PyCharm 2021.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.

This site uses Akismet to reduce spam. Learn how your comment data is processed.