Stop Using print() Every Time In Python ??? Use pprint() Instead

Enter our benevolent saviour pprint()

pprint is built-in, so we don’t need to install anything.

from pprint import pprint

pprint(x)
  • one simple from pprint import pprint line is needed
  • it makes our messy data more human-readable
  • it doesn’t require us to manually make it human-readable

Can’t we just write a for loop instead?

Let’s say we have a even more messy data structure.

x = {
  'name':'tom',
  'dad': {'name': 'jerry',
          'dad':{'name':'greg'},
          'mom':{'name':'susie'}
          },
  'mom': {'name': 'mary'},
  'wife': {'name': 'susan'},
  'son': {'name': 'tim',
          'dad':{'name':'tom'},
          'mom':{'name':'susan'},
          'wife':{'name':'cassie'},
          'daughter': {'name':'lala',
                        'husband': 'bobo'
                        }
          }
}

Here we have some screwed up family tree as an example with multiple multiple levels of nesting.

We have 2 options to visualize this:

  1. we manually write a recursive function to print out everything
  2. we use pprint

Read More

Tags: pprint Python