Search code examples
pythonpython-3.xpprint

PPrint not working (Python)?


I'm trying to use Python's pprint on a dictionary but for some reason it isn't working. Here's my code (I'm using PyCharm Pro as my IDE):`

from pprint import pprint
message = "Come on Eileen!"
count = {}

for character in message:
    count.setdefault(character, 0)
    count[character] += 1

pprint(count)

And here's my output:

{' ': 2, '!': 1, 'C': 1, 'E': 1, 'e': 3, 'i': 1, 'l': 1, 'm': 1, 'n': 2, 'o': 2}

Any help with this would be appreciated.


Solution

  • The output is entirely correct and expected. From the pprint module documentation:

    The formatted representation keeps objects on a single line if it can, and breaks them onto multiple lines if they don’t fit within the allowed width.

    Bold emphasis mine.

    You could set the width keyword argument to 1 to force every key-value pair being printed on a separate line:

    >>> pprint(count, width=1)
    {' ': 2,
     '!': 1,
     'C': 1,
     'E': 1,
     'e': 3,
     'i': 1,
     'l': 1,
     'm': 1,
     'n': 2,
     'o': 2}