Summary: In this tutorial, we will learn to print a normal or nested dictionary data structure line by line in Python.

When we output any inbuilt data structures (such as list, dictionary, etc) in Python, it gets printed in a single line.

For instance, here we are printing a nested dictionary in Python and by default, it prints in the same row.

user = { 'id': 1007, 
         'name': "Pencil Programmer", 
         'address': { 'city': 'Goa', 
                      'pincode': 567006
                    }
       } 
       
print(user)    #outputs {'id': 1007, 'name': 'Pencil Programmer', 'address': {'city': 'Goa', 'pincode': 567006}}

The output is readable now but as the dictionary grows, the same output will become difficult to interpret.

Hence it is important to print key-values of the dictionary (especially if it is nested) on separate lines for better readability of the output data.

Let’s see two methods to do so in Python.

Method 1: Using for loop

In this method, using the for loop we loop through the key-value pairs of the given dictionary and output them line by line as a pair as per the iteration.

If we find that a particular value is a nested dictionary, we recursively iterate through its key-value pairs in order to ouput them.

#dictionary
user = { 'id': 1007, 
         'name': "Pencil Programmer", 
         'address': { 'city': 'Goa', 
                      'pincode': 567006
                    }
       } 

#recursive function to print the dictionary line by line       
def print_dict(dictionary, indent=4):
    print('{')
    
    for key, value in dictionary.items():
        #recurse if the value is a dictionary
        if type(value) is dict:
            print(' '*indent, key, ": ", end='')
            print_dict(value, indent+4)
        else:
            print(' '*indent, key, ": ", value)
            
    print(' '*(indent-4), '}')
            
print_dict(user)

Output:

{
     id :  1007
     name :  Pencil Programmer
     address :  {
         city :  Goa
         pincode :  567006
     }
 }

Method 2: Using json.dumps()

In this method, we use the dumps method of the inbuilt Python’s json module to print a dictionary line by line.

The dumps method converts the given dictionary into a structured JSON string of the specified indentation.

import json

#dictionary
user = { 'id': 1007, 
         'name': "Pencil Programmer", 
         'address': { 'city': 'Goa', 
                      'pincode': 567006
                    }
       } 
 
#print dictionary in JSON format        
print(json.dumps(user, indent=4))

Outputs:

{
    "id": 1007,
    "name": "Pencil Programmer",
    "address": {
        "city": "Goa",
        "pincode": 567006
    }
}

It is important to provide the value for the indent parameter in the dumps call statement otherwise the output data will not be formatted by line.

These are the two simple ways to make a Python dictionary look nice in the output.

Leave a Reply

14 + 4 =