Explain Codes LogoExplain Codes Logo

How to pretty print nested dictionaries?

python
dataframe
pandas
pretty-printing
Anton ShumikhinbyAnton Shumikhin·Sep 28, 2024
TLDR

Pretty print a nested dictionary using json.dumps():

import json # Here's a dict for all you cat lovers cats = {'Fluffy': {'Breed': 'Persian', 'Color': 'White'}, 'Tom': {'Breed': 'Siamese', 'Color': 'Black'}} print(json.dumps(cats, indent=4))
  • json.dumps() converts dict to a JSON string.
  • indent=4: Gives it a neat 4-space indentation, because we all like our tabs like we like our pizzas -- Deep and Spacious!

Leveling Up: pprint & PyYAML

pprint: For those who like it deep

The pprint module's PrettyPrinter comes with depth control. How deep you go with dict is now in your hands!

from pprint import PrettyPrinter # Here's something shady shady_dicts = {'Level 1': {'Sub-Level1': {'Sub-Sub-Level1': 'You have reached the core'}}} pp = PrettyPrinter(depth=2) pp.pprint(shady_dicts)
  • PrettyPrinter lets you customize pretty printer instances.

PyYAML: Make it comprehensible for humans

import yaml # Intricate family tree? No problem! family_tree = {'Grandpa': {'Father': {'You': 'Composer of YAML'}}} print(yaml.dump(family_tree, allow_unicode=True))
  • yaml.dump() transforms the dictionary to human-readable YAML format.
  • Use allow_unicode parameter to enable support for emojis, because who doesn't love emojis!

Advanced pretty printing techniques

Handling custom objects

json.dumps() offers a neat little trick for custom objects:

# Ever tried fitting a square peg in a round hole? print(json.dumps(my_custom_dict, indent=4, default=str))
  • default=str will handle non-serializable objects your dict might throw at it.

Recursive pretty print function

For mental gymnasts out there, you can use recursion for nested dictionaries:

# Because running in circles is fun! def pretty_print(d, indent=0): for key, value in d.items(): print('\t' * indent + str(key)) if isinstance(value, dict): pretty_print(value, indent+1) else: print('\t' * (indent+1) + str(value)) pretty_print(nested_dict)
  • Recursive function adapts to any dict depth.
  • \t gives consistent indentation, making code as clean as a freshly washed laundry.

Sorting keys

Because life is too short for finding keys in a dict:

# Let's organize that mess! print(json.dumps({'b': 2, 'a': 1}, indent=4, sort_keys=True))
  • sort_keys=True will put everything in order, making it easier to find the keys in the literal dictionary of your data.