Pretty Printing Dictionaries in Python
This tutorial will show you how to pretty print dictionaries in Python. Pretty printing means presenting some printed content in a more readable format or style.
pprint()
Pretty printing dictionaries
in Python
pprint
is a Python module that provides the ability to pretty print Python data types to make them more readable. This module also supports pretty printing dictionaries.
In pprint
the module, there is a function with the same name pprint()
, which is used to pretty-print a given string or object.
First, we declare an array of dictionaries. After that, pprint.pprint()
we pretty-print them using the function.
import pprint
dct_arr = [
{"Name": "John", "Age": "23", "Country": "USA"},
{"Name": "Jose", "Age": "44", "Country": "Spain"},
{"Name": "Anne", "Age": "29", "Country": "UK"},
{"Name": "Lee", "Age": "35", "Country": "Japan"},
]
pprint.pprint(dct_arr)
Output:
[{'Age': '23', 'Country': 'USA', 'Name': 'John'},
{'Age': '44', 'Country': 'Spain', 'Name': 'Jose'},
{'Age': '29', 'Country': 'UK', 'Name': 'Anne'},
{'Age': '35', 'Country': 'Japan', 'Name': 'Lee'}]
By comparison, here is the output of a normal print()
statement.
[
{"Name": "John", "Age": "23", "Country": "USA"},
{"Name": "Jose", "Age": "44", "Country": "Spain"},
{"Name": "Anne", "Age": "29", "Country": "UK"},
{"Name": "Lee", "Age": "35", "Country": "Japan"},
]
pprint()
The output is definitely easier to read. What it does is break up each dictionary element in the array after the comma, while also sorting the dictionary values by key.
If you don't want your key-value pairs to be sorted by the key, then pprint()
is not suitable to use because its sorting mechanism is built into the function.
Also note that pprint()
pretty printing of nested objects, including nested dictionaries, will not work. So if you want your values to be nested, this is not the solution for this problem either.
json.dumps()
Pretty printing a dictionary
in Python using
In the Python json
module, there is a dumps()
function called which can convert a Python object into a JSON string. In addition to the conversion, it also formats the dictionary into a pretty JSON format, so this is a viable way to pretty-print the dictionary by converting it to JSON first.
dumps()
The function accepts three arguments for pretty printing: the object to be converted, a boolean value sort_keys
that determines whether the elements should be sorted by key, and indent
, which specifies the number of spaces to indent.
For this solution, we will use the same example dictionary as above. sort_keys
Set to False
to disable sorting and indent
to 4
a space.
import json
dct_arr = [
{"Name": "John", "Age": "23", "Country": "USA"},
{"Name": "Jose", "Age": "44", "Country": "Spain"},
{"Name": "Anne", "Age": "29", "Country": "UK"},
{"Name": "Lee", "Age": "35", "Country": "Japan"},
]
print(json.dumps(dct_arr, sort_keys=False, indent=4))
Output:
[
{
"Age": "23",
"Country": "USA",
"Name": "John"
},
{
"Age": "44",
"Country": "Spain",
"Name": "Jose"
},
{
"Age": "29",
"Country": "UK",
"Name": "Anne"
},
{
"Age": "35",
"Country": "Japan",
"Name": "Lee"
}
]
It is much more readable than pprint()
the output of the function, although it takes up a few more lines, since it is in JSON format.
What if the given value has a nested dictionary inside it? Let's edit this example and see the output.
import json
dct_arr = [
{"Name": "John", "Age": "23", "Residence": {"Country": "USA", "City": "New York"}},
{"Name": "Jose", "Age": "44", "Residence": {"Country": "Spain", "City": "Madrid"}},
{"Name": "Anne", "Age": "29", "Residence": {"Country": "UK", "City": "England"}},
{"Name": "Lee", "Age": "35", "Residence": {"Country": "Japan", "City": "Osaka"}},
]
print(json.dumps(dct_arr, sort_keys=False, indent=4))
Output:
[
{
"Name": "John",
"Age": "23",
"Residence": {
"Country": "USA",
"City": "New York"
}
},
{
"Name": "Jose",
"Age": "44",
"Residence": {
"Country": "Spain",
"City": "Madrid"
}
},
{
"Name": "Anne",
"Age": "29",
"Residence": {
"Country": "UK",
"City": "England"
}
},
{
"Name": "Lee",
"Age": "35",
"Residence": {
"Country": "Japan",
"City": "Osaka"
}
}
]
It's clear that using json.dump()
supports beautiful JSON nested dictionaries, which look visually clean and very readable even when nested.
yaml.dump()
Pretty printing dictionaries
in Python
Another way to print a dictionary is to use the yaml
module's dump()
print function. It works json.dumps()
the same as the print function, but uses the YAML format instead of JSON.
First, pip
install the YAML module using .
pip install pyyaml
Or if using Python 3 and pip3
installing the YAML module.
pip3 install pyyaml
Let's try this with the same nesting example we used in the JSON example.
Note the new parameter default_flow_style
, which determines whether the output style of dump should be inline
or block
. In this case, the output should be in blocks, and since we want it to be readable, we set this parameter to False
.
import yaml
dct_arr = [
{"Name": "John", "Age": "23", "Residence": {"Country": "USA", "City": "New York"}},
{"Name": "Jose", "Age": "44", "Residence": {"Country": "Spain", "City": "Madrid"}},
{"Name": "Anne", "Age": "29", "Residence": {"Country": "UK", "City": "England"}},
{"Name": "Lee", "Age": "35", "Residence": {"Country": "Japan", "City": "Osaka"}},
]
print(yaml.dump(dct_arr, sort_keys=False, default_flow_style=False))
Output:
- Name: John
Age: '23'
Residence:
Country: USA
City: New York
- Name: Jose
Age: '44'
Residence:
Country: Spain
City: Madrid
- Name: Anne
Age: '29'
Residence:
Country: UK
City: England
- Name: Lee
Age: '35'
Residence:
Country: Japan
City: Osaka
In conclusion, whether the YAML dump()
function is more readable than JSON dumps()
is a matter of personal opinion. It depends on personal preference or what type of output is needed. When it comes to more complex data structures or nested objects, both functions pprint
are better than the output of .
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Writing logs to a file in Python
Publish Date:2025/05/06 Views:133 Category:Python
-
This tutorial will show you how to write logs to files in Python. Use the module in Python logging to write logs to files Logging is used to debug a program and find out what went wrong. logging The log module is used to log data to a file
Comparing two dates in Python
Publish Date:2025/05/06 Views:97 Category:Python
-
This tutorial explains how to compare two dates in Python. There are multiple ways to determine which date is greater, so the tutorial also lists different sample codes to illustrate the different methods. Comparing two dates in Python usin
Reload or unimport modules in Python
Publish Date:2025/05/06 Views:59 Category:Python
-
Modules allow us to store definitions of different functions and classes in Python files, which can then be used in other files. pandas , NumPy , scipy , Matplotlib are the most widely used modules in Python. We can also create our own modu
Pausing program execution in Python
Publish Date:2025/05/06 Views:157 Category:Python
-
This tutorial will demonstrate various ways to pause a program in Python. Pausing the execution of a program or application is used in different scenarios, such as when a program requires user input. We may also need to pause the program fo
Importing modules from a subdirectory in Python
Publish Date:2025/05/06 Views:191 Category:Python
-
This tutorial will explain various ways to import modules from subdirectories in Python. Suppose we have a file in a subdirectory of our project directory and we want to import this file and use its methods in our code. We can import files
Sleeping for a number of milliseconds in Python
Publish Date:2025/05/06 Views:124 Category:Python
-
In this tutorial, we will look at various ways to pause or suspend the execution of a program in Python for a given amount of time. Let's say we want to pause the execution of a program for a few seconds to let the user read instructions ab
Python Numpy.pad Function
Publish Date:2025/05/06 Views:104 Category:Python
-
In Python, we have NumPy the array module to create and use arrays. Arrays can have different sizes and dimensions. Padding is a useful method that can be used to compensate for the size of an array. We can mutate an array and add some padd
Generating Random Colors in Python
Publish Date:2025/05/06 Views:136 Category:Python
-
In the digital world, colors are represented in different formats. RGB, Hexadecimal format are just some of the commonly used formats. In this tutorial, we will learn how to generate random colors in Python. When we talk about generating ra
Getting the name of a class in Python
Publish Date:2025/05/06 Views:84 Category:Python
-
Just like object constructors, classes can be defined as user-defined prototypes for creating objects. class Classes can be created using the keyword . A class is a data structure that can contain both data members and member methods. This