The Wayback Machine - https://web.archive.org/web/20240717024743/https://www.geeksforgeeks.org/pprint-data-pretty-printer-python/
Open In App

pprint : Data pretty printer in Python

Last Updated : 06 Oct, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

This article is about a pretty useful built-in module in Python, pprint.

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

Let us consider an example:




# A python code without pprint
import requests
  
def geocode(address):
    resp = requests.get(url, params = {'address': address})
    return resp.json()
  
# calling geocode function
data = geocode('India gate')
  
# printing json response
print(data)


The above code is for getting the geocode information of a place using Google Maps API in JSON format.

The output of above program looks like this:

{'status': 'OK', 'results': [{'address_components': [{'long_name': 'Rajpath', 'types': ['route'], 
'short_name': 'Rajpath'}, {'long_name': 'India Gate', 'types': ['political', 'sublocality', 
'sublocality_level_1'], 'short_name': 'India Gate'}, {'long_name': 'New Delhi', 'types': 
['locality', 'political'], 'short_name': 'New Delhi'}, {'long_name': 'New Delhi', 
'types': ['administrative_area_level_2', 'political'], 'short_name': 'New Delhi'}, {'long_name': 
'Delhi', 'types': ['administrative_area_level_1', 'political'], 'short_name': 'DL'}, {'long_name': 
'India', 'types': ['country', 'political'], 'short_name': 'IN'}, {'long_name': '110001', 'types': 
['postal_code'], 'short_name': '110001'}], 'geometry': {'location': {'lng': 77.2295097, 'lat': 28.612912}, 
'viewport': {'northeast': {'lng': 77.2308586802915, 'lat': 28.6142609802915}, 'southwest': {'lng': 
77.22816071970848, 'lat': 28.6115630197085}}, 'location_type': 'APPROXIMATE'}, 'types': 
['establishment', 'point_of_interest'], 'formatted_address': 'Rajpath, India Gate, New Delhi, Delhi 110001, 
India', 'place_id': 'ChIJC03rqdriDDkRXT6SJRGXFwc'}]}

As you can see, this output is not properly indented which affects readability for nested data structures.

Now, consider the code below:




# A python code with pprint
import requests
from pprint import pprint
  
def geocode(address):
    resp = requests.get(url, params = {'address': address})
    return resp.json()
  
# calling geocode function
data = geocode('India gate')
  
# pretty-printing json response
pprint(data)


The output of above code looks like this:

{'results': [{'address_components': [{'long_name': 'Rajpath',
                                      'short_name': 'Rajpath',
                                      'types': ['route']},
                                     {'long_name': 'India Gate',
                                      'short_name': 'India Gate',
                                      'types': ['political',
                                                'sublocality',
                                                'sublocality_level_1']},
                                     {'long_name': 'New Delhi',
                                      'short_name': 'New Delhi',
                                      'types': ['locality', 'political']},
                                     {'long_name': 'New Delhi',
                                      'short_name': 'New Delhi',
                                      'types': ['administrative_area_level_2',
                                                'political']},
                                     {'long_name': 'Delhi',
                                      'short_name': 'DL',
                                      'types': ['administrative_area_level_1',
                                                'political']},
                                     {'long_name': 'India',
                                      'short_name': 'IN',
                                      'types': ['country', 'political']},
                                     {'long_name': '110001',
                                      'short_name': '110001',
                                      'types': ['postal_code']}],
              'formatted_address': 'Rajpath, India Gate, New Delhi, Delhi '
                                   '110001, India',
              'geometry': {'location': {'lat': 28.612912, 'lng': 77.2295097},
                           'location_type': 'APPROXIMATE',
                           'viewport': {'northeast': {'lat': 28.6142609802915,
                                                      'lng': 77.2308586802915},
                                        'southwest': {'lat': 28.6115630197085,
                                                      'lng': 77.22816071970848}}},
              'place_id': 'ChIJC03rqdriDDkRXT6SJRGXFwc',
              'types': ['establishment', 'point_of_interest']}],
 'status': 'OK'}

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

All we did was to import the pprint function of pprint module. And use pprint() function rather than the print function!

This blog is contributed by Nikhil Kumar.



Similar Reads

pprint function in SymPy
The pprint() takes two arguments, one is an expression and the other is the use_unicode argument, the use_unicode is a boolean argument. In case the terminal does not support Unicode then ASCII printer is used by default or else we need to pass use_unicode=False. And to call this function the user needs to first import the SymPy library. Here the S
1 min read
Pretty Print JSON in Python
JSON is a javascript notation of storing and fetching the data. Data is usually stored in JSON, XML or in some other database. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Read, Write and Parse JSON using Python Pretty Print JSON Whenever d
2 min read
Pretty print Linked List in Python
Creating custom data types can be tricky, especially when you want to use it like any other data type. Linked List can be thought of as an example of a custom data type. In other languages, if you want to print the linked list, you would define a separate print function, something like pprint but it looks kind of odd, right? Like it would be great
3 min read
Pretty Printing XML in Python
XML stands for Extensible Markup Language and is used to encode a document that can be understandable by both humans and machines. Data stored in XML format is easy to understand and easy to modify. There are three main things that have to keep in mind when you are using XML – Simplicity, Generality, and Usability. Pretty Printing XML using xml.dom
2 min read
Python - Pretty Print JSON
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will learn about JSON pretty print What is JSON?JSON (JavaScript Object Notation) is a text-based data format that is interchangeable with many programming languages.
5 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
How to Pretty Print an Entire Pandas Series or DataFrame?
In this article, we are going to see how to Pretty Print the entire pandas Series / Dataframe. There are various pretty print options are available for use with this method. Here we will discuss 3 ways to Pretty Print the entire Pandas Dataframe: Use pd.set_options() methodUse pd.option_context() methodUse options.display() MethodCreating DataFrame
3 min read
Pretty-Printing in BeautifulSoup
Prerequisite: requestsBeautifulSoup In this article, we will learn about how to print pretty in BeautifulSoup Using Python. The requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scraping, requests are must be learned for proceeding further with these technologies. When one mak
2 min read
How to convert unstructured data to structured data using Python ?
Prerequisite: What is Unstructured Data? Sometimes machine generates data in an unstructured way which is less interpretable. For example, Biometric Data, where an employee does Punch - IN or OUT several times with mistakes. We can not analyze the data and identify the mistakes unless it's in a tabular form. In this article, we will take unstructur
5 min read
Python - Convert Tick-by-Tick data into OHLC (Open-High-Low-Close) Data
In this post, we'll explore a Python pandas package feature. We frequently find queries about converting tick-by-tick data to OHLC (Open, High, Low and Close). Using pandas kit this can be done with minimum effort. The OHLC data is used over a unit of time (1 day, 1 hour etc.) to perform a technical analysis of price movement. The First Step: The f
2 min read
three90RightbarBannerImg