Printing data in nice format in python

This post introduces how to print data in a nice formatted way in python using the built-in module pprint.

The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a well-formatted and more readable way.

>>> from pprint import pprint

>>> my_list = ["1","2","3","4"]

>>> print(my_list)

['1', '2', '3', '4']

>>> pprint(my_list)

['1', '2', '3', '4']

# You may wonder the output of pprint is not working, because it looks the same as the output of print.

# however, 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.

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

>>> pprint(my_list, width =1)






Note that if you use import pprint, instead of fromp pprint import pprint, use the following:

>>> import pprint 
>>> my_list = ["1","2","3","4"]  
>>> pprint.pprint(my_list)

see below for an example of printing json data.

>>> from pprint import pprint

>>> my_json = { "fruit": "Apple", "size": "Large", "color": "Red" }

>>> print(my_json)

{'color': 'Red', 'fruit': 'Apple', 'size': 'Large'}

>>> pprint(my_json)

{'color': 'Red', 'fruit': 'Apple', 'size': 'Large'}

>>> pprint(my_json, width =1)

{'color': 'Red',

 'fruit': 'Apple',

 'size': 'Large'}

>>> from pprint import pprint

>>> my_json = {'children': [], 'lastName': 'Smith', 'phoneNumbers': [{'number': '212 555-1234', 'type': 'home'}, {'number': '646 555-4567', 'type': 'office'}, {'number': '123 456-7890', 'type': 'mobile'}], 'address': {'city': 'New York', 'postalCode': '10021-3100', 'state': 'NY', 'streetAddress': '21 2nd Street'}, 'firstName': 'John', 'age': 27}

>>> print(my_json)

{'children': [], 'lastName': 'Smith', 'phoneNumbers': [{'number': '212 555-1234', 'type': 'home'}, {'number': '646 555-4567', 'type': 'office'}, {'number': '123 456-7890', 'type': 'mobile'}], 'address': {'city': 'New York', 'streetAddress': '21 2nd Street', 'state': 'NY', 'postalCode': '10021-3100'}, 'firstName': 'John', 'age': 27}

>>> pprint(my_json)

{'address': {'city': 'New York',

             'postalCode': '10021-3100',

             'state': 'NY',

             'streetAddress': '21 2nd Street'},

 'age': 27,

 'children': [],

 'firstName': 'John',

 'lastName': 'Smith',

 'phoneNumbers': [{'number': '212 555-1234', 'type': 'home'},

                  {'number': '646 555-4567', 'type': 'office'},

                  {'number': '123 456-7890', 'type': 'mobile'}]}


As you can see, the output is now well formatted and more readable.

What we did is to import the pprint function of pprint module. And use pprint() function rather than the print function:)

Leave a Reply

Your email address will not be published. Required fields are marked *