How can I pretty print a dictionary with depth of ~4 in Python? I tried pretty printing with pprint()
, but it did not work:
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)
I simply want an indentation ("\t"
) for each nesting, so that I get something like this:
key1
value1
value2
key2
value1
value2
etc.
How can I do this?
Answers
To achieve pretty-printing of a dictionary with custom indentation for nested levels in Python, pprint
might not always offer the flexibility you need for deep nesting. Instead, you can use a custom function to handle indentation and formatting according to your specific requirements.
Here’s a function that will pretty-print a dictionary with nested levels and use tabs ("\t"
) for indentation:
def pretty_print_dict(d, indent=0):
"""
Recursively prints a dictionary with custom indentation for each level.
Parameters:
- d: Dictionary to be printed.
- indent: The current level of indentation (used for recursion).
"""
for key, value in d.items():
print("\t" * indent + str(key))
if isinstance(value, dict):
pretty_print_dict(value, indent + 1)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
pretty_print_dict(item, indent + 1)
else:
print("\t" * (indent + 1) + str(item))
else:
print("\t" * (indent + 1) + str(value))
# Example usage
mydict = {
'key1': {
'key1.1': 'value1.1',
'key1.2': {
'key1.2.1': 'value1.2.1',
'key1.2.2': ['value1.2.2', {'key1.2.2.1': 'value1.2.2.1'}]
}
},
'key2': 'value2'
}
pretty_print_dict(mydict)
Explanation
-
Function Definition:
pretty_print_dict(d, indent=0)
:d
: The dictionary to print.indent
: The current level of indentation.
-
Loop through Items:
- Keys: Print the key with the current level of indentation.
- Values: Handle values based on their type:
- Dicts: Recursively call
pretty_print_dict
with increased indentation. - Lists: Iterate over the list. For dictionary items within the list, call
pretty_print_dict
recursively. For other types, print them with increased indentation. - Other Types: Print values with increased indentation.
- Dicts: Recursively call
-
Example Usage: The
mydict
dictionary contains nested dictionaries and lists to demonstrate the function’s capability to handle different structures.
Output
For the example dictionary, the output will be:
key1
key1.1
value1.1
key1.2
key1.2.1
value1.2.1
key1.2.2
value1.2.2
key1.2.2.1
value1.2.2.1
key2
value2
This approach gives you control over the formatting and handles complex nesting and list elements in a dictionary. You can adjust the indentation level or format as needed.