How to pretty print nested dictionaries?
⚡TLDR
Pretty print a nested dictionary using json.dumps():
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!
PrettyPrinterlets you customize pretty printer instances.
PyYAML: Make it comprehensible for humans
yaml.dump()transforms the dictionary to human-readable YAML format.- Use
allow_unicodeparameter 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:
default=strwill 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:
- Recursive function adapts to any dict depth.
\tgives consistent indentation, making code as clean as a freshly washed laundry.
Sorting keys
Because life is too short for finding keys in a dict:
sort_keys=Truewill put everything in order, making it easier to find the keys in the literal dictionary of your data.
Linked
Was this article helpful?