The pprint module (pretty print) is a built-in utility that formats complex data structures like dictionaries, lists, or JSON in a readable way with proper indentation and line breaks. It’s useful for debugging and inspecting nested data.
from pprint import pprint
data = {
'name': 'Leo',
'age': 20,
'hobbies': ['reading', 'coding', 'traveling'],
'address': {
'city': 'New Delhi',
'country': 'India'
}
}
pprint(data)
Output
{'address': {'city': 'New Delhi', 'country': 'India'},
'age': 20,
'hobbies': ['reading', 'coding', 'traveling'],
'name': 'Leo'}
Explanation: pprint(data): formats it neatly with indentation and line breaks, making it easier to read.
Example: Printing JSON from an API
Without pprint
import requests
def geocode(address):
url = "https://maps.googleapis.com/maps/api/geocode/json"
resp = requests.get(url, params={'address': address})
return resp.json()
data = geocode('India Gate')
print(data)
Output:
{'status': 'OK', 'results': [{'address_components': [{'long_name': 'Rajpath', 'types': ['route'], 'short_name': 'Rajpath'}, ... }]}
Explanation:
- Imports requests to call the Google Maps API.
- geocode(address): sends a request and returns the JSON response as a Python dictionary.
- data = geocode('India Gate'): gets location details.
With pprint
import requests
from pprint import pprint
def geocode(address):
url = "https://maps.googleapis.com/maps/api/geocode/json"
resp = requests.get(url, params={'address': address})
return resp.json()
data = geocode('India Gate')
pprint(data)
{'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']},
...
],
'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'}
Explanation:
- pprint: Displays data neatly.
- geocode(address): Sends a request to the API with the given address and returns the JSON response as a Python dictionary.
- data = geocode('India Gate'): Gets location details for India Gate.
- pprint(data): Prints the data in a readable, well-formatted way instead of one long line.