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!

+17


source to share


5 answers


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)

      

+22


source


My favorite way:



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

      

+15


source


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
>>>

      

+5


source


Agree, "beautiful" is very subjective. See if this helps what I used to debug the dict

for i in inventory_things.keys():
    logger.info('Key_Name:"{kn}", Key_Value:"{kv}"'.format(kn=i, kv=inventory_things[i]))

      

0


source


I wrote this function for printing simple dictionaries:

def dictToString(dict):
  return str(dict).replace(', ','\r\n').replace("u'","").replace("'","")[1:-1]

      

0


source







All Articles