Monday, June 26, 2017

Summer of code 2017: Python, Pretty printing with pprint in Python


As explained in my Summer of code 2017: Python post I decided to pick up Python

This post is about using pprint to pretty print.


The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. 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. Construct PrettyPrinter objects explicitly if you need to adjust the width constraint.

Let's take a look at a dictionary

First we do a regular print

>>> stocks ={
'TGT' :  '51.33', 
'AAPL': '147.48',
'MSFT':  '71.49',
'F'   :  '11.12', 
'INTC':  '34.37'}
>>> print(stocks)
{'TGT': '51.33', 'AAPL': '147.48', 'MSFT': '71.49', 'F': '11.12', 'INTC': '34.37'}


As you can see everything is printed on one line


You can print on multiple lines by using a loop and format

stocks ={
'TGT' :  '51.33', 
'AAPL': '147.48',
'MSFT':  '71.49',
'F'   :  '11.12', 
'INTC':  '34.37'}
>>> for key in stocks:
    print("{key} = {value}".format(key=key, value=stocks[key]))

    
TGT = 51.33
AAPL = 147.48
MSFT = 71.49
F = 11.12
INTC = 34.37


Finally let's take a look at what pprint does

>>> stocks ={
'TGT' :  '51.33', 
'AAPL': '147.48',
'MSFT':  '71.49',
'F'   :  '11.12', 
'INTC':  '34.37'}
>>> from pprint import pprint as pp
>>> pp(stocks)
{'AAPL': '147.48',
 'F': '11.12',
 'INTC': '34.37',
 'MSFT': '71.49',
 'TGT': '51.33'}


As you can see, each key value pair is on one line


What about lists?

A list of integers looks pretty much the same

>>> a =  [ [2],[4], [1]]
>>> print(a)
[[2], [4], [1]]
>>> pp(a)
[[2], [4], [1]]


A list of strings is a different story

>>> l ="SpaceX successfully launches and recovers second Falcon 9 in 48 hours".split()
>>> print(l)
['SpaceX', 'successfully', 'launches', 'and', 'recovers', 'second', 'Falcon', '9',
 'in', '48', 'hours']
>>> pp(l)
['SpaceX',
 'successfully',
 'launches',
 'and',
 'recovers',
 'second',
 'Falcon',
 '9',
 'in',
 '48',
 'hours']
>>> 

As you can see that prints the elements on a separate line



The pprint module also supports some keyword parameters like indent, width, depth, let's take a look at indent



>>> import pprint
>>> l ="SpaceX successfully launches and recovers second Falcon 9 in 48 hours".split()
>>> pp = pprint.PrettyPrinter(indent=6)
>>> 
>>> pp.pprint(l)
[     'SpaceX',
      'successfully',
      'launches',
      'and',
      'recovers',
      'second',
      'Falcon',
      '9',
      'in',
      '48',
      'hours']
>>> 

As you can see the values are moved to the right by 6 spaces


Make sure to look at the examples in the docs online to see what other things pprint supports


 

No comments: