How to print a dictionary well in Python?
I just started learning python and I am creating a text game. I want an inventory system, but I can't print a dictionary without its ugliness. 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])
Thank!
source to share
I like the module pprint
included in Python. It can be used to print an object or to format it.
import pprint
# Prints the nicely formatted dictionary
pprint.pprint(dictionary)
# Sets 'pretty_dict_str' to
pretty_dict_str = pprint.pformat(dictionary)
But it looks like you are printing out an inventory, which will most likely look like something similar to the following:
def print_inventory(dct):
print("Items held:")
for item, amount in dct.iteritems():
print("{} ({})".format(item, amount))
inventory = {
"shovels": 3,
"sticks": 2,
"dogs": 1,
}
print_inventory(inventory)
which prints:
Items held:
shovels (3)
sticks (2)
dogs (1)
source to share
Here is one liner I would use. (Edit: works for things that are not JSON serializable too)
print("\n".join("{}\t{}".format(k, v) for k, v in dictionary.items()))
Explanation: This iterates over the keys and values โโof the dictionary, producing a formatted string such as key + tab + value for each. And it "\n".join(...
puts new lines between all these lines, forming a new line.
Example:
>>> dictionary = {1: 2, 4: 5, "foo": "bar"}
>>> print("\n".join("{}\t{}".format(k, v) for k, v in dictionary.items()))
1 2
4 5
foo bar
>>>
source to share