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.

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)

Leave a Comment