close

How to print out a dictionary nicely in Python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to print out a dictionary nicely in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to print out a dictionary nicely in Python?

  1. How to print out a dictionary nicely in Python?

    I like the pprint module (Pretty Print) included in Python. It can be used to either print the object, or format a nice string version of it.

  2. print out a dictionary nicely in Python

    I like the pprint module (Pretty Print) included in Python. It can be used to either print the object, or format a nice string version of it.

Method 1

I like the pprint module (Pretty Print) included in Python. It can be used to either print the object, or format a nice string version of it.

import pprint

# Prints the nicely formatted dictionary
pprint.pprint(dictionary)

# Sets 'pretty_dict_str' to the formatted string value
pretty_dict_str = pprint.pformat(dictionary)

But it sounds like you are printing out an inventory, which users will likely want shown as something more like the following:

def print_inventory(dct):
    print("Items held:")
    for item, amount in dct.items():  # dct.iteritems() in Python 2
        print("{} ({})".format(item, amount))

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

print_inventory(inventory)

which prints:

Items held:
shovels (3)
sticks (2)
dogs (1)

Method 2

My favorite way:

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read