Skip to content Skip to sidebar Skip to footer

How To Print Out A Dictionary Nicely In Python?

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 hav

Solution 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 2print("{} ({})".format(item, amount))

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

print_inventory(inventory)

which prints:

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

Solution 2:

My favorite way:

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

Solution 3:

Here's the one-liner I'd use. (Edit: works for things that aren't JSON-serializable too)

print("\n".join("{}\t{}".format(k, v) for k, v in dictionary.items()))

Explanation: This iterates through the keys and values of the dictionary, creating a formatted string like key + tab + value for each. And "\n".join(... puts newlines between all those strings, forming a new string.

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

Edit 2: Here's a sorted version.

"\n".join("{}\t{}".format(k, v) for k, v insorted(dictionary.items(), key=lambda t: str(t[0])))

Solution 4:

I would suggest to use beeprint instead of pprint.

Examples:

pprint

{'entities': {'hashtags': [],
              'urls': [{'display_url': 'github.com/panyanyany/beeprint',
                        'indices': [107, 126],
                        'url': 'https://github.com/panyanyany/beeprint'}],'user_mentions': []}}

beeprint

{
  'entities': {
    'hashtags': [],
    'urls': [
      {
        'display_url': 'github.com/panyanyany/beeprint',
        'indices': [107, 126],
        'url': 'https://github.com/panyanyany/beeprint'}],
      },
    ],
    'user_mentions': [],
  },
}

Solution 5:

Yaml is typically much more readable, especially if you have complicated nested objects, hierarchies, nested dictionaries etc:

First make sure you have pyyaml module:

pip install pyyaml

Then,

import yaml
print(yaml.dump(my_dict))

Post a Comment for "How To Print Out A Dictionary Nicely In Python?"