- Pretty-print with pprint in Python
- 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
- Python: Pretty Print a Dict (Dictionary) – 4 Ways
- What are Python Dictionaries?
- Pretty Print a Dict in Python with pprint
- Pretty Print a Dict in Python with JSON
- Pretty Print a Nested Dictionary in Python
- Save a Pretty Printed Dictionary to a File
- Conclusion
Pretty-print with pprint in Python
In Python, you can pretty-print objects such as lists ( list ) and dictionaries ( dict ) with the pprint module.
In the sample code, the list of dictionaries is used as an example. The pprint module is included in the standard library, so no additional installation is required, but you need to import it.
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]>]
See the following article for details about the print() function.
The textwrap module is useful for wrapping or truncating long strings, not lists or dictionaries.
Basic usage of pprint
The print() function outputs the elements of a list or dictionary on a single line without any line breaks.
With pprint.pprint() , each element of the list will be broken into a new line, as shown below, making it easier to read.
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 the pretty-printed output to a string ( str ) instead of directly printing 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 breaks to fit the specified number of characters. The default value is width=80 .
pprint.pprint(l, width=40) # [ # 'Name': 'Alice XXX', # 'Points': [80, 20]>, # # 'Name': 'Bob YYY', # 'Points': [90, 10]>, # # 'Name': 'Charlie ZZZ', # 'Points': [70, 30]>]
If width is large, no newline is inserted, and the output is the same as print() .
A line breaks at an element of a list or a dictionary, not between the 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) # [ # 'Name': 'Alice ' # 'XXX', # 'Points': [80, # 20]>, # # 'Name': 'Bob ' # 'YYY', # 'Points': [90, # 10]>, # # '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) # [, # , # ]
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 depend on the number of characters specified by width .
pprint.pprint(l, depth=2, width=40) # [ # 'Name': 'Alice XXX', # 'Points': [. ]>, # # 'Name': 'Bob YYY', # 'Points': [. ]>, # # '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]>]
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 can fit within width are printed on a single line. This setting is particularly useful 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()
You can convert dictionaries and lists to strings using str() . It produces a one-line string without line breaks, similar to the output of print() .
s_normal = str(l) print(s_normal) # [, , ] print(type(s_normal)) #
You can use pprint.pformat() to get the output of pprint.pprint() as the string str .
s_pp = pprint.pformat(l) print(s_pp) # [, # , # ] print(type(s_pp)) #
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 can be difficult to read when printed with print() . For better readability, consider using 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)) #
Python: Pretty Print a Dict (Dictionary) – 4 Ways
In this tutoria, you’ll learn how to use Python to pretty print a dict (dictionary). You’ll learn how to use the pprint library as well as the json library to do this. You’ll also learn how to pretty print nested dictionaries in Python. Finally, you’ll learn how to save a pretty printed dict in Python to a file.
Dictionaries are a key component of working with data in Python, including with data loaded from the internet. Many APIs return data in JSON format, which is very similar to the formatting of Python dictionaries. Dictionaries provide incredibly helpful ways in which you can store and retrieve data. However, they can be a bit tricky to read. Because of this, it’s often helpful to be able to print out your dictionaries in a more human-readable format. Without further ado, let’s take a look at what you’ll learn!
The Quick Answer: Use the json library
What are Python Dictionaries?
Python dictionaries are data structures that use key:value pairs to hold and retrieve data. Keys are unique, in Python dictionaries, and must be made up of immutable data types (such as strings or integers), while values can be made up of anything, including additional dictionaries.
Let’s take a look at what a dictionary looks like in Python:
We can retrieve a value if we know a dictionary’s key. For example, if we wanted to retrieve the value for age , we could simply write: print(sample_dict.get(‘age’)) , which would return 31 .
Now that we have an understanding of what Python dictionaries are, let’s take a look at how to pretty print them.
Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.
Pretty Print a Dict in Python with pprint
Python comes with a built-in library called pprint , which stands for pretty-print. Using this library, we can print out more nicely formatted data structures, including dictionaries.
The pprint library allows us to specify a number of different parameters, including the following:
- indent : the number of spaces to indent each line, where the default value is 1
- width : the maximum caharacters that are allowed on a single line, where the default is None (meaning, the maximum)
- depth : the number of levels to show while using nested data types, where the default is None (meaning that all levels of depth are shown)
- stream : used to specify an output stream and can be used to save to a file
- compact : If set to True , the values will be printed on single lines, to a certain width
- sort_dicts : if True , it prints the key-value pairs according to an alphabetical order of the keys. Defaults to True
Let’s load a dictionary and see how we can pretty print it using Python:
# Pretty Print a Dictionary using pprint import pprint sample_dict = pprint.pprint(sample_dict) # Returns: #
In the next section, you’ll learn how to use the JSON library to pretty print a Python dict.
Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.
Pretty Print a Dict in Python with JSON
As mentioned earlier, Python dictionaries carry a lot of similar characteristics with JSON objects. Because of this, we can use the JSON library to return a formatted JSON string.
Built into the json library is a function called .dumps() , which dumps a string object. Let’s take a look at what the .dumps() function looks like and what parameters it takes:
- sort_keys which sorts a dictionary’s keys and defaults to False
- indent : which lets Python know how many spaces to indent levels by
Let’s use the same dictionary as above and pretty print it using Python’s json library:
# Pretty Print a Dictionary using json import json sample_dict = , 'Joe': > pretty = json.dumps(sample_dict, indent=4) print(pretty) # Returns: #
We can see here that this returns a very similar printed dictionary, with a key difference: the list is also printed on seperate lines, making it easier to read. This, of course, is a much prettier way to print your dictionaries.
In the next section, you’ll learn how to pretty print a nested dictionary in Python.
Want to learn how to pretty print a JSON file using Python? Learn three different methods to accomplish this using this in-depth tutorial here.
Pretty Print a Nested Dictionary in Python
In many cases, your dictionaries will be complex. You may even encounter dictionaries that contain other dictionaries. For example, you may have a dictionary that contains information on different people. Each key of the top-level dictionary will represent a person’s name and the value will be a different dictionary that will describe key attributes of a person.
Because of the complexity of dictionaries you may encounter, to better understand their structure, you may wish to print them out a way that more appropriately describes their structure.
Using the json library, this is actually very easy! It actually works in the same way as printing a normal dictionary. Let’s take a look:
# Pretty Print a Nested Dictionary using json import json sample_dict = , 'Joe': > pretty = json.dumps(sample_dict, indent=4, sort_keys=True) print(pretty) # Returns: # < # "Joe": < # "age": 40, # "books": [ # "Lord of the Flies" # ], # "gender": "male" # >, # "Nik": < # "age": 31, # "books": [ # "Harry Potter", # "Lord of the Rings" # ], # "gender": "male" # ># >
In the next section, you’ll learn how to save a pretty printed dictionary to a file.
Save a Pretty Printed Dictionary to a File
Finally, let’s take a look at how to save a pretty printed dict to a file. We can use the pprint library to accomplish this, with the help of a context manager.
Let’s see how this can be done using Python:
# Save a pretty printed dict to a file import pprint sample_dict = , 'Joe': > with open('path_to_file', 'w') as file_name: pprint.pprint(sample_dict, file_name)
We use a context manager using the open() function to link to a particular file where we want to save our dictionary and then use the ‘w’ parameter to say we want to write to the file. We then pass the dictionary and this file_name into the pprint() function to save it to a file.
Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.
Conclusion
In this post, you learned how to use Python to pretty print a dict. You learned how to do this using the pprint and json libraries, and learned the ways in which these two approaches differ. You also learned how to pretty print nested dictionaries in Python as well as how to save pretty printed dictionaries to a file.
To learn more about the pprint library, check out the official documentation here.