Pretty print of nested dictionaries in Python
In this text, we are going to see how to obtain a pretty print of nested dictionaries using two modules of Python. To obtain the pretty print of nested dictionaries the two modules Json and pprint will be used. These two modules are in-built so, you need not worry about installing them to your codespace. A few examples of pretty print of nested dictionaries have been discussed in this text for a better and faster understanding of this concept of pretty print.
Json:
Json is a module in Python. We are going to use this module to get a pretty print of a nested dictionary as shown below.
# import the module import json # Create the dictionary dictionary = {'John':{'Gender':'Male','Country':'Australia','Occupation':'Wrestler','Parents':['Teddy Hall','Renee Young Hall']} ,'Jack':{'Gender':'Male','Country':'America','Occupation':'Dancer','Parents':['George Heymann','Nikki Natalya']}} # Use the module json.dumps() to create the pretty print Pretty_print=json.dumps(dictionary) # print the dictionary print(Pretty_print)
Output:
In this, the pretty print doesn’t look clearly readable. So, there is a method in the Json library known as indent that can make the pretty print look more attractive.
# import the module import json # Create the dictionary dictionary = {'John':{'Gender':'Male','Country':'Australia','Occupation':'Wrestler','Parents':['Teddy Hall','Renee Young Hall']} ,'Jack':{'Gender':'Male','Country':'America','Occupation':'Dancer','Parents':['George Heymann','Nikki Natalya']}} # Use the module json.dumps to create the pretty print Pretty_print=json.dumps(dictionary,indent=2) # print the dictionary print(Pretty_print)
pprint:
Now, we will learn to create a pretty print of a nested dictionary with the help of the pprint module in Python. This is the simplest method to create a pretty print of a nested dictionary. The method has been implemented below.
# import the module import pprint # Create the dictionary dictionary = {'John':{'Gender':'Male','Country':'Australia','Occupation':'Wrestler','Parents':['Teddy Hall','Renee Young Hall']} ,'Jack':{'Gender':'Male','Country':'America','Occupation':'Dancer','Parents':['George Heymann','Nikki Natalya']}} # Use the module pprint.pprint to create the pretty print pprint.pprint(dictionary)
Output:
This way you can create the pretty print of a nested dictionary in Python.
Leave a Reply