Fix Python – How to print out a dictionary nicely in Python?

Question

Asked By – Raphael Huang

I’ve just started to learn python and I’m building a text game. I want an inventory system, but I can’t seem to print out the dictionary without it looking ugly.

This is what I have so far:

def inventory():
    for numberofitems in len(inventory_content.keys()):
        inventory_things = list(inventory_content.keys())
        inventory_amounts = list(inventory_content.values())
        print(inventory_things[numberofitems])

Now we will see solution for issue: How to print out a dictionary nicely in Python?


Answer

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)

This question is answered By – foslock

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0