note.nkmk.me

Pretty-print with pprint in Python

Posted: 2021-09-08 / Tags: Python, List, Dictionary

In Python, you can pretty-print objects such as lists list and dictionaries dict with the pprint module.

This article describes the following contents.

  • Basic usage of pprint
  • Specify the output width (number of characters): width
  • Specify the output depth: depth
  • Specify the indent width: indent
  • Reduce line breaks: compact
  • Convert to string: pprint.pformat()
  • Example: Pretty-print a list of lists

To wrap or truncate long strings instead of lists or dictionaries, the textwrap module is useful. See the following article.

In the sample code, the pprint module is imported as follows, and the list of dictionaries is used as an example. The pprint module is included in the standard library, so there is no need to install it additionally.

import pprint

l = [{'Name': 'Alice XXX', 'Age': 40, 'Points': [80, 20]}, 
     {'Name': 'Bob YYY', 'Age': 20, 'Points': [90, 10]},
     {'Name': 'Charlie ZZZ', 'Age': 30, 'Points': [70, 30]}]
Sponsored Link

Basic usage of pprint

The normal print() function prints out the elements of a list or dictionary on a single line without any line breaks.

print(l)
# [{'Name': 'Alice XXX', 'Age': 40, 'Points': [80, 20]}, {'Name': 'Bob YYY', 'Age': 20, 'Points': [90, 10]}, {'Name': 'Charlie ZZZ', 'Age': 30, 'Points': [70, 30]}]

With pprint.pprint(), each element of the list will be broken into a new line as shown below, making it easier to read.

pprint.pprint(l)
# [{'Age': 40, 'Name': 'Alice XXX', 'Points': [80, 20]},
#  {'Age': 20, 'Name': 'Bob YYY', 'Points': [90, 10]},
#  {'Age': 30, 'Name': 'Charlie ZZZ', 'Points': [70, 30]}]

The line break position is determined by the argument settings described below.

Note that, as shown in the example above, the elements of the dictionary are sorted in the order of the keys. If the parameter sort_dicts, added in Python 3.8, is set to False (default: True), the order of the dictionaries is kept, but in earlier versions they are always sorted.

If you want to convert it to a string str instead of outputting it, use pprint.pformat() described below.

Specify the output width (number of characters): width

The output width (number of characters) can be specified with width.

The line is broken so that a line fits the specified number of characters. The default value is width=80.

pprint.pprint(l, width=40)
# [{'Age': 40,
#   'Name': 'Alice XXX',
#   'Points': [80, 20]},
#  {'Age': 20,
#   'Name': 'Bob YYY',
#   'Points': [90, 10]},
#  {'Age': 30,
#   'Name': 'Charlie ZZZ',
#   'Points': [70, 30]}]

If width is large, no newline is inserted, and the output is the same as print().

pprint.pprint(l, width=200)
# [{'Age': 40, 'Name': 'Alice XXX', 'Points': [80, 20]}, {'Age': 20, 'Name': 'Bob YYY', 'Points': [90, 10]}, {'Age': 30, 'Name': 'Charlie ZZZ', 'Points': [70, 30]}]

A line is broken at an element of a list or a dictionary, not between key and value of a dictionary, nor in the middle of a number. Therefore, it does not always fit into the width of the number of characters specified by width.

Note that strings may be broken into a new line for each word.

pprint.pprint(l, width=1)
# [{'Age': 40,
#   'Name': 'Alice '
#           'XXX',
#   'Points': [80,
#              20]},
#  {'Age': 20,
#   'Name': 'Bob '
#           'YYY',
#   'Points': [90,
#              10]},
#  {'Age': 30,
#   'Name': 'Charlie '
#           'ZZZ',
#   'Points': [70,
#              30]}]

Specify the output depth: depth

The output depth can be specified with depth. The depth here means the depth of nesting.

Elements nested deeper than the specified value are printed with the ellipsis ....

pprint.pprint(l, depth=1)
# [{...}, {...}, {...}]

pprint.pprint(l, depth=2)
# [{'Age': 40, 'Name': 'Alice XXX', 'Points': [...]},
#  {'Age': 20, 'Name': 'Bob YYY', 'Points': [...]},
#  {'Age': 30, 'Name': 'Charlie ZZZ', 'Points': [...]}]

The default value is depth=None, and all elements are output.

You can specify both width and depth at the same time. The depth specifies the depth of the data structure, not the number of lines. The line break positions are depends on the number of characters specified by width.

pprint.pprint(l, depth=2, width=40)
# [{'Age': 40,
#   'Name': 'Alice XXX',
#   'Points': [...]},
#  {'Age': 20,
#   'Name': 'Bob YYY',
#   'Points': [...]},
#  {'Age': 30,
#   'Name': 'Charlie ZZZ',
#   'Points': [...]}]

Specify the indent width: indent

The indent width can be specified with indent. The default value is indent=1

pprint.pprint(l, indent=4, width=4)
# [   {   'Age': 40,
#         'Name': 'Alice '
#                 'XXX',
#         'Points': [   80,
#                       20]},
#     {   'Age': 20,
#         'Name': 'Bob '
#                 'YYY',
#         'Points': [   90,
#                       10]},
#     {   'Age': 30,
#         'Name': 'Charlie '
#                 'ZZZ',
#         'Points': [   70,
#                       30]}]
Sponsored Link

Reduce line breaks: compact

By default, all elements of a list or dictionary break lines if they do not fit into width.

l_long = [list(range(10)), list(range(100, 110))]

print(l_long)
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [100, 101, 102, 103, 104, 105, 106, 107, 108, 109]]

pprint.pprint(l_long, width=40)
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
#  [100,
#   101,
#   102,
#   103,
#   104,
#   105,
#   106,
#   107,
#   108,
#   109]]

If compact is set to True, elements that fit into width are printed on a single line. It is better to use compact=True for lists with many elements.

pprint.pprint(l_long, width=40, compact=True)
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
#  [100, 101, 102, 103, 104, 105, 106,
#   107, 108, 109]]

Note that compact was added in Python 3.4, so it cannot be used in earlier versions.

Convert to string: pprint.pformat()

Dictionaries and lists can be converted to the string with str(). In this case, they are converted to a one-line string without newline, as in the output of print().

s_normal = str(l)
print(s_normal)
# [{'Name': 'Alice XXX', 'Age': 40, 'Points': [80, 20]}, {'Name': 'Bob YYY', 'Age': 20, 'Points': [90, 10]}, {'Name': 'Charlie ZZZ', 'Age': 30, 'Points': [70, 30]}]

print(type(s_normal))
# <class 'str'>

You can use pprint.pformat() to get the output of pprint.pprint() as the string str.

s_pp = pprint.pformat(l)
print(s_pp)
# [{'Age': 40, 'Name': 'Alice XXX', 'Points': [80, 20]},
#  {'Age': 20, 'Name': 'Bob YYY', 'Points': [90, 10]},
#  {'Age': 30, 'Name': 'Charlie ZZZ', 'Points': [70, 30]}]

print(type(s_pp))
# <class 'str'>

The parameters of pprint.pformat() is the same as pprint.pprint().

s_pp = pprint.pformat(l, depth=2, width=40, indent=2)
print(s_pp)
# [ { 'Age': 40,
#     'Name': 'Alice XXX',
#     'Points': [...]},
#   { 'Age': 20,
#     'Name': 'Bob YYY',
#     'Points': [...]},
#   { 'Age': 30,
#     'Name': 'Charlie ZZZ',
#     'Points': [...]}]

Example: Pretty-print a list of lists

A list of lists are hard to read with print(), so use pprint.pprint().

l_2d = [list(range(10)), list(range(10)), list(range(10))]

print(l_2d)
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

pprint.pprint(l_2d)
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
#  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
#  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

As mentioned above, where to start a new line is determined by the number of characters specified by width.

If the number of elements is small, it fits into the default output width width=80, so there is no line break.

l_2d = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

print(l_2d)
# [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

pprint.pprint(l_2d)
# [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

If an appropriate width is specified, the line will be broken.

pprint.pprint(l_2d, width=20)
# [[0, 1, 2],
#  [3, 4, 5],
#  [6, 7, 8]]

If you want to get it as a string, use pprint.pformat().

s = pprint.pformat(l_2d, width=20)
print(s)
# [[0, 1, 2],
#  [3, 4, 5],
#  [6, 7, 8]]

print(type(s))
# <class 'str'>
Sponsored Link
Share

Related Categories

Related Articles