Sling Academy
Home/Python/Python: How to Pretty Print a Deeply Nested Dictionary (Basic and Advanced Examples)

Python: How to Pretty Print a Deeply Nested Dictionary (Basic and Advanced Examples)

Last updated: February 13, 2024

Introduction

Python, known for its simplicity and readability, sometimes requires a little extra help when it comes to dealing with deeply nested dictionaries. This guide will show you how to navigate these complexities and print them in a readable format using both basic and advanced techniques.

Dealing with deeply nested dictionaries in Python can quickly become challenging, especially when attempting to visualize or debug their structure. By ‘pretty printing’, we mean printing complex data structures in a way that is easy to read and understand. Fortunately, Python offers several methods to achieve this, ranging from built-in functionalities to external libraries that can handle even the most complex of structures.

Basic Example Using pprint

The pprint module in Python is the first tool in our arsenal. It is a built-in module designed to “pretty-print” Python data structures. Let’s start with a basic example:

import pprint
simple_dict = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': {'f': 4}}}
pprint.pprint(simple_dict)

Output:

{'a': 1, 'b': 2, 'c': {'d': 3, 'e': {'f': 4}}}

This doesn’t look much different from the regular print function, but it becomes much more useful as the dictionaries become more nested.

Adjusting pprint Parameters

We can adjust the pprint parameters to better handle complex structures. The indent parameter is particularly useful:

import pprint
detailed_dict = {'level1': {'level2': {'level3': {'level4': 'deep value'}}}}
pprint.pprint(detailed_dict, indent=4)

Output:

{'level1': {'level2': {'level3': {'level4': 'deep value'}}}}

By increasing the indent, each nested level becomes much more readable.

Using json.dumps for Pretty Printing

Another method to pretty print nested dictionaries is using the json module, specifically the json.dumps method. This method is particularly useful for dictionaries that are JSON compatible. Here’s an example:

import json
nested_dict = {'a': {'b': {'c': {'d': ['e', 'f', 'g']}}}}
print(json.dumps(nested_dict, indent=4))

Output:

{
"a": {
"b": {
"c": {
"d": [
"e",
"f",
"g"
]
}
}
}
}

The indent parameter in json.dumps works similarly to pprint, making it easy to adjust the visual structure of the output.

Advanced: Custom Pretty Printer

For more control over how dictionaries are printed, you can write a custom pretty printer. This gives you the flexibility to format your output exactly how you want it. The following example demonstrates a simple custom pretty printer:

def custom_pretty_printer(d, indent=0):
for key, value in d.items():
print(' ' * indent + str(key) + ':', end='')
if isinstance(value, dict):
print()
custom_pretty_printer(value, indent+1)
else:
print(' ' + str(value))
nested_dict = {'a': 1, 'b': {'c': 2, 'd': {'e': 3}}}
custom_pretty_printer(nested_dict)

Output:

a: 1
b:
c: 2
d:
e: 3

This example demonstrates a recursive function that traverses the dictionary and prints each key-value pair, increasing the indent level when a dictionary is encountered. This approach is powerful but requires more effort to implement and customize.

Conclusion

Pretty printing deeply nested dictionaries in Python is crucial for development and debugging. Whether you use the pprint module, the json.dumps method, or write your own custom printer, you have a variety of tools at your disposal to make complex data structures readable. Experiment with these examples to find the best fit for your needs.

Next Article: Python RuntimeError: directory changed during iteration

Previous Article: Python: How to get a random item from a dictionary

Series: Working with Dict, Set, and Tuple in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots