Skip to content

Python print dictionary nicely | Example code

  • by

Best way to print a dictionary nicely use JSON in Python. JSON serializer is probably pretty good at nested dictionaries. You have to import a JSON module for this.

import json

print(json.dumps(dictionary, indent=4, sort_keys=True))

Example print dictionary nicely in Python

Simple example code.

import json

inventory = {
    "shovels": 3,
    "sticks": 2,
    "dogs": 1,
}

print(json.dumps(inventory, indent=4, sort_keys=True))

Output:

Python print dictionary nicely

Example with a nested dictionary

import json

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

print(json.dumps(people, indent=4, sort_keys=True))

Output:

{
    "1": {
        "age": "27",
        "name": "John",
        "sex": "Male"
    },
    "2": {
        "age": "22",
        "name": "Marie",
        "sex": "Female"
    }
}

To print a dictionary nicely in Python, you can use a loop to iterate through its key-value pairs and format the output in a readable way. Here’s a simple example:

my_dict = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

for key, value in my_dict.items():
    print(f'{key}: {value}')

You can adjust the formatting to your preference. For example, you could use tabs or additional spaces for indentation to make it even more readable.

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 *