What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Pretty Print Dictionary in Python: pprint & json (with examples)

  • Feb 13, 2023
  • 5 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abrar Ahmed
Pretty Print Dictionary in Python: pprint & json (with examples)

Whether you are a beginner or an experienced Python programmer, having the ability to format your data in a visually appealing manner is essential for debugging, testing, and overall code readability. In this article, we will explore how to print a pretty dictionary in python and how it can be used to make your data easier to understand.

What is Pretty Printing in Python Dictionary?

Let's first revise what is a dictionary in python. A dictionary is a built-in data structure that stores key-value pairs. The keys in a dictionary must be unique, immutable (cannot be changed) objects, such as strings or numbers. The values can be of any data type and can be duplicated. These are enclosed by curly braces {} and separated by a colon.

Now, let's move to the main topic.

Pretty printing, commonly referred to as "syntax highlighting," is a Python feature that enables the presentation of code in a more aesthetically pleasing and readable fashion. This is accomplished by differentiating between various types of code elements, including keywords, comments, and variable names, using various colors, font styles, and indentations.

Python's pretty printing dictionaries are useful because it improves data readability. Working with dictionaries, particularly those with a large number of key-value pairs, can make it difficult to understand the structure and organization of the data. Pretty printing makes data easier to understand and work with by displaying it in a more organized and easy-to-read format.

Another reason to use pretty printing for dictionaries is to aid in debugging. When attempting to identify and correct code errors, it can be beneficial to view the data in a more detailed format. Developers can quickly identify any issues or problems with the data.

It can also be helpful for data visualization, where it will be easier to identify patterns and trends, making it a valuable tool for data analysis and exploration.

How to Pretty Print Dictionary in Python?

A number of libraries, including pprint, json, and yaml, can be used to achieve nice printing in python. These libraries offer a wide range of formatting options, making it simple to alter the code's appearance to meet the particular requirements of the project.

Using pprint

The Python pprint (pretty-print) module provides a function to display complex data structures like dictionaries in a more readable format. The function pprint() takes an object as input and returns a string representation of the object with appropriate indentation and line breaks.

You must first import the module before you can use pprint to pretty print a dictionary. Once imported, you can print your dictionary using the pprint() function.

Example:

import pprint

data = {'name': 'Abrar', 'age': 20, 'address': 'Bangalore'}

pprint.pprint(data)

 

Output:

{'address': 'Bangalore', 'age': 20, 'name': 'Abrar'}

 

You can also customize the pprint module's output by using the pprint.PrettyPrinter() class, which allows you to specify options such as output width, indentation level, and whether or not to sort the keys. You can, for example, use the width attribute to specify the maximum width of the output:

import pprint

data = {'name': 'Abrar', 'age': 20, 'address': 'Bangalore'}

pprint.PrettyPrinter(width=20).pprint(data)

 

Output:

{'address': 'Bangalore',
 'age': 20,
 'name': 'Abrar'}

 

You can also use the indent attribute to set the number of spaces used for indentation and you can use the sort_dicts attribute to sort the keys alphabetically before printing.

import pprint

data = {'name': 'Abrar', 'age': 20, 'address': 'Bangalore'}
pprint.PrettyPrinter(indent=4,sort_dicts=True).pprint(data)

 

Output:

{'address': 'Bangalore', 'age': 20, 'name': 'Abrar'}

 

Using json

Python's json library allows you to convert a Python dictionary to a JSON string and vice versa. This makes it, like the pprint module, a powerful tool for displaying dictionaries in a human-readable format.

To use the json library to pretty print a dictionary, you must first import it. After importing the dictionary, use the json.dumps() method to convert it to a JSON string, passing in the indent parameter to specify the number of spaces to use for indentation. 

Example:

import json

data = {'name': 'Abrar', 'age': 20, 'address': 'Bangalore'}

print(json.dumps(data, indent=4))

 

Output:

{
    "name": "Abrar",
    "age": 20,
    "address": "Bangalore"
}

 

This will output the dictionary in a more readable format, with each key-value pair on a new line and indented to show the hierarchy of the data.

You can also use the json.dump() method to write the JSON string to a file 

import json
data = {'name': 'Abrar', 'age': 20, 'address': 'Bangalore'}
with open("data.json", "w") as f:
    json.dump(data, f, indent=4)

 

The json method also provides you a sort_keys parameter to sort keys alphabetically before printing the dictionary

import json
data = {'name': 'Abrar', 'age': 20, 'address': 'Bangalore'}
print(json.dumps(data, indent=4, sort_keys=True))

 

Output:

{
    "address": "Bangalore",
    "age": 20,
    "name": "Abrar"
}

 

Pretty Printing a nested Dictionary

In Python, you can use either the pprint module or the json library to pretty print a nested dictionary. To do this, the pprint module includes a built-in function called pprint(). It can be used in the same way as flat dictionaries.

Here is the code for that:

import pprint

data = {'name': 'Abrar Ahmed', 'age': 20, 'address': {'street': 'East End', 'city': 'Bangalore', 'state': 'Karnataka'}}

pprint.pprint(data)

 

Output:

{'address': {'city': 'Bangalore', 'state': 'Karnataka', 'street': 'East End'},
 'age': 20,
 'name': 'Abrar Ahmed'}

 

The nested dictionary will be output in a more readable format, with each key-value pair on a new line and indented to show the data hierarchy.

You can also use the json library to convert the nested dictionary to a JSON string and then print it with the indent parameter set to increase the indentation of the inner nested elements. As an example:

import json

data = {'name': 'Abrar Ahmed', 'age': 20, 'address': {'street': 'East End', 'city': 'Bangalore', 'state': 'Karnataka'}}

print(json.dumps(data, indent=4))

 

Output:

{
    "name": "Abrar Ahmed",
    "age": 20,
    "address": {
        "street": "East End",
        "city": "Bangalore",
        "state": "Karnataka"
    }
}

 

Conclusion

Being able to present a dictionary in a readable format is essential for any programmer. We discussed two popular methods to pretty print a dictionary in python with examples. Both pprint and json works in similar manner but pprint is more commonly used.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abrar Ahmed
An ambivert individual with a thirst for knowledge and passion to achieve. Striving to connect Artificial Intelligence in all aspects of life. I am also an avid coder and partake in coding challenges all the time on Leetcode and CodeChef.