Python pprint Exercise - Specify the indentation while printing a nested dictionary
Write a Python program that specifies the indentation while printing a nested dictionary using the pprint module.
"indent" (default 1) specifies the amount of indentation added for each nesting level.
Sample Solution:
Python Code:
import pprint
print("\nNested dictionary with specific indent:")
nested_dict = {
's1': {
'a': 2,
'c': 1,
'b': 3
},
's2': {
'f': 3,
'e': 4,
'd': 6
},
's3': {
'g': 17,
'h': 18,
'i': 9
},
's4': {
'a': 7,
'j': 8,
'k': 19
}
}
pp = pprint.PrettyPrinter(indent=4)
print("\nIndent = 4")
pp.pprint(nested_dict)
print("\nIndent = 15")
pp = pprint.PrettyPrinter(indent=15)
pp.pprint(nested_dict)
Sample Output:
Nested dictionary with specific indent: Indent = 4 { 's1': {'a': 2, 'b': 3, 'c': 1}, 's2': {'d': 6, 'e': 4, 'f': 3}, 's3': {'g': 17, 'h': 18, 'i': 9}, 's4': {'a': 7, 'j': 8, 'k': 19}} Indent = 15 { 's1': {'a': 2, 'b': 3, 'c': 1}, 's2': {'d': 6, 'e': 4, 'f': 3}, 's3': {'g': 17, 'h': 18, 'i': 9}, 's4': {'a': 7, 'j': 8, 'k': 19}}
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Specify the width of the output while printing a list, dictionary.
Next: Fetch information about a project.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics