9

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.

TomCho
  • 3,204
  • 6
  • 32
  • 83
Roby Leahy
  • 113
  • 1
  • 5
  • 1
    What makes you think it is not working? What did you expect instead? That's the correct output for `pprint()`; the output fits on one line. – Martijn Pieters Aug 20 '16 at 22:22
  • 2
    I'm reading through Automate the Boring Stuff with Python, in chapter 5 it talks about pprint, gives an example of code (almost identical to mine) but shows to output to be key-pair values being printed on separate lines. *(I just realised the reason it wasn't doing that was because my string wasn't long enough) – Roby Leahy Aug 20 '16 at 22:44

3 Answers3

17

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}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

You have to specify the second parameter i.e

pprint.pprint(count, width=1)

Or in your case

pprint(count, width=1)

Output:

{' ': 2,
 '!': 1,
 'C': 1,
 'E': 1,
 'e': 3,
 'i': 1,
 'l': 1,
 'm': 1,
 'n': 2,
 'o': 2}
Joel
  • 353
  • 2
  • 7
-2

I am having the same issue when practicing, then I realized I am running the old characterCount.py again and again instead of running the new pretty character Count.py file. Try to click the run button on the top and choose the right file and run again.