Why to use Pretty Print in Python?

Dhairye Kataria
3 min readJan 12, 2021
Photo by Ferenc Almasi on Unsplash

Dictionaries in Python can get long, which often gets messy and makes it harder to read for a human. Just printing a dictionary onto the terminal doesn’t work. So, How can we make it readable for a programmer? Fortunately, There’s a library in the vast collection of libraries for python which can do exactly what we want. Let’s see how we can do this.

The pprint (“Pretty-Print”) Module:

The pprint module has some functions which are helpful to get a cleaner display of the items in the dictionary than what print() provides. The two functions are pprint() and pformat(). First, we will take a look over how the pprint() function can enhance the readability of a dictionary as compared to the print() function in a program and the pformat() function in the end.

print():

message = 'It was a bright cold day in April, and the clocks were striking thirteen.'count = {}for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1print(count)

This is a program for counting the number of times a particular character has appeared in the given message and stores the result in the form of a dictionary and prints it by using the print() function. And the output we get from this program looks something like this:

{' ': 13, ',': 1, '.': 1, 'A': 1, 'I': 1, 'a': 4, 'c': 3, 'b': 1, 'e': 5, 'd': 3, 'g': 2, 'i': 6, 'h': 3, 'k': 2, 'l': 3, 'o': 2, 'n': 4, 'p': 1, 's': 3, 'r': 5, 't': 6, 'w': 2, 'y': 1}

Which is not readable at all but actually a disaster.

pprint():

import pprintmessage = 'It was a bright cold day in April, and the clocks were striking thirteen.'count = {}for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1pprint.pprint(count)

This is the same program and prints the same dictionary but now using the pprint() function from the pprint module instead. Let’s see what magic does this function do:

{' ': 13,
',': 1,
'.': 1,
'A': 1,
'I': 1,
'a': 4,
'c': 3,
'b': 1,
'e': 5,
'd': 3,
'g': 2,
'i': 6,
'h': 3,
'k': 2,
'l': 3,
'o': 2,
'n': 4,
'p': 1,
's': 3,
'r': 5,
't': 6,
'w': 2,
'y': 1}

This time, when the program is run, the output looks much cleaner, with the keys sorted.

The pprint.pprint() function is especially helpful when the dictionary itself contains nested lists or dictionaries.

pformat():

If you want to obtain the prettified text as a string value instead of displaying it on the screen, call pprint.pformat() instead. These two lines are equivalent to each other:

pprint.pprint(someDictionaryValue) print(pprint.pformat(someDictionaryValue))

Link to the pprint module documentation:

Thanks for reading this article. I hope that this might have helped you in some way. Don’t forget to clap this article and respond if you have some suggestions.

--

--

Dhairye Kataria
0 Followers

A computer science student. I write whatever interests me. 😉