w3resource

Python pprint Exercise - Specify the width of the output while printing a list, dictionary


3. Pprint with Custom Width

Write a Python program that specifies the width of the output while printing a list, dictionary using the pprint module.

"width" (default 80) specifies the desired maximum number of characters per line in the output. If a structure cannot be formatted within the width constraint, a best effort will be made.

Sample Solution:

Python Code:

import pprint
colors = ["Red", "Green", "Blue", "White", "Pink"]
print("List with specific width:")
pp = pprint.PrettyPrinter(width=20)
pp.pprint(colors)
print("\nDictionary with specific width:")
nested_dict = {
    'd1': {
        'a': 2,
        'c': 1,
        'b': 3
    },
    'd2': {
        'f': 3,
        'e': 4,
        'd': 6
    },
    'd3': {
        'g': 17,
        'h': 18,
        'i': 9
    }
}
pp.pprint(nested_dict)

Sample Output:

List with specific width:
['Red',
 'Green',
 'Blue',
 'White',
 'Pink']

Dictionary with specific width:
{'d1': {'a': 2,
        'b': 3,
        'c': 1},
 'd2': {'d': 6,
        'e': 4,
        'f': 3},
 'd3': {'g': 17,
        'h': 18,
        'i': 9}}

Flowchart:

Flowchart: Specify the width of the output while printing a list, dictionary.

For more Practice: Solve these Related Problems:

  • Write a Python program that prints a long list and a nested dictionary using pprint, setting the width parameter to 50, and observe how the output format changes.
  • Write a Python function that accepts any data structure and pretty-prints it with a user-specified width, then test it with different width values.
  • Write a Python script to generate a dictionary with very long string values and use pprint to print the dictionary with a custom width that forces line breaks.
  • Write a Python program to compare the output of pprint with different width settings for the same nested structure and document the differences.

Go to:


Previous: Sort the keys of a dictionary before printing it using the pprint module.
Next: Specify the indentation while printing a nested dictionary.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.