0
0
Pythonprogramming~5 mins

Formatting structured data in Python

Choose your learning style9 modes available
Introduction

We format structured data to make it easy to read and understand. It helps us share data clearly with others or save it in a neat way.

When you want to print data like lists or dictionaries in a readable way.
When saving data to a file so others can open and understand it easily.
When sending data over the internet in a format like JSON.
When debugging, to see the structure of your data clearly.
When you want to organize data output for reports or logs.
Syntax
Python
import json

json.dumps(data, indent=number_of_spaces)

# or

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

json.dumps() converts Python data into a formatted string.

The indent parameter adds spaces to make the output easier to read.

Examples
Prints the dictionary as a compact JSON string without extra spaces.
Python
import json

my_data = {'name': 'Alice', 'age': 30}
print(json.dumps(my_data))
Prints the dictionary with indentation of 2 spaces for better readability.
Python
import json

my_data = {'name': 'Alice', 'age': 30}
print(json.dumps(my_data, indent=2))
Formats a list containing numbers and a dictionary with 4 spaces indentation.
Python
import json

my_list = [1, 2, 3, {'a': 4, 'b': 5}]
print(json.dumps(my_list, indent=4))
Sample Program

This program formats a dictionary with nested list into a nicely indented JSON string and prints it.

Python
import json

person = {
    'name': 'John',
    'age': 25,
    'hobbies': ['reading', 'gaming', 'hiking']
}

formatted = json.dumps(person, indent=4)
print(formatted)
OutputSuccess
Important Notes

Use json.dumps() for formatting data as a string.

You can also use json.dump() to write formatted data directly to a file.

Indentation helps humans read data but is ignored by computers when parsing.

Summary

Formatting structured data makes it easier to read and share.

Use json.dumps() with indent to add spaces and new lines.

This is useful for printing, saving, or sending data clearly.