Bird
Raised Fist0
Pythonprogramming~10 mins

Formatting structured data in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Formatting structured data
Start with data structure
Choose format: JSON, CSV, etc.
Use formatting function
Generate formatted string
Output or save formatted data
End
This flow shows how to take a data structure, choose a format, format it, and output the result.
Execution Sample
Python
import json

person = {"name": "Anna", "age": 28, "city": "Paris"}

json_string = json.dumps(person, indent=2)
print(json_string)
This code formats a Python dictionary into a nicely indented JSON string and prints it.
Execution Table
StepActionInputOutput/Result
1Define dictionaryperson = {"name": "Anna", "age": 28, "city": "Paris"}person holds the dictionary
2Call json.dumps with indent=2person dictionaryReturns JSON string formatted with 2 spaces indentation
3Print the JSON stringFormatted JSON string{ "name": "Anna", "age": 28, "city": "Paris" }
4EndN/AProgram ends after printing
💡 All steps complete, JSON string printed with indentation
Variable Tracker
VariableStartAfter json.dumpsFinal
person{"name": "Anna", "age": 28, "city": "Paris"}{"name": "Anna", "age": 28, "city": "Paris"}{"name": "Anna", "age": 28, "city": "Paris"}
json_stringN/A{ "name": "Anna", "age": 28, "city": "Paris" }{ "name": "Anna", "age": 28, "city": "Paris" }
Key Moments - 2 Insights
Why do we use json.dumps instead of print(person)?
print(person) shows the dictionary in Python format without indentation. json.dumps formats it as a JSON string with indentation, making it easier to read, as shown in execution_table step 2 and 3.
What does the indent=2 argument do?
indent=2 tells json.dumps to add line breaks and 2 spaces per indentation level, making the output easier to read. This is shown in the output column of step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output after step 2?
AAn error message
BThe original dictionary printed as is
CA JSON string with indentation
DAn empty string
💡 Hint
Check the Output/Result column in row for step 2 in execution_table
At which step is the formatted JSON string printed to the screen?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the Action column and Output/Result for step 3 in execution_table
If we remove indent=2 from json.dumps, how would the output change?
AOutput would be the same with indentation
BOutput would be a compact JSON string without line breaks
COutput would be a Python dictionary
DProgram would crash
💡 Hint
Think about what indent=2 does as explained in key_moments and execution_table step 2
Concept Snapshot
Formatting structured data means converting data like dictionaries into readable strings.
Use json.dumps() to convert Python dicts to JSON strings.
The indent parameter adds spaces and line breaks for readability.
Without indent, JSON is compact and hard to read.
Formatted data is easier to share and understand.
Full Transcript
This example shows how to format structured data in Python using the json module. We start with a dictionary named person. Using json.dumps with indent=2, we convert the dictionary into a nicely formatted JSON string with line breaks and spaces. Then we print this string. The execution table traces each step: defining the dictionary, formatting it, printing the result, and ending the program. The variable tracker shows how the dictionary stays the same, and the json_string variable holds the formatted JSON after calling json.dumps. Key moments clarify why json.dumps is used and what indent=2 does. The visual quiz tests understanding of the output at each step and the effect of indent. The concept snapshot summarizes the main points about formatting structured data for readability.

Practice

(1/5)
1. What does the indent parameter do in json.dumps() when formatting structured data?
easy
A. Adds spaces and new lines to make the output easier to read
B. Converts data into a binary format
C. Removes all spaces and new lines for compact output
D. Encrypts the JSON data for security

Solution

  1. Step 1: Understand the purpose of json.dumps()

    This function converts Python data into a JSON string.
  2. Step 2: Role of indent parameter

    The indent parameter adds spaces and new lines to format the JSON string nicely for readability.
  3. Final Answer:

    Adds spaces and new lines to make the output easier to read -> Option A
  4. Quick Check:

    indent = readable JSON [OK]
Hint: Remember: indent means pretty print with spaces [OK]
Common Mistakes:
  • Thinking indent compresses JSON
  • Confusing indent with encryption
  • Assuming indent changes data content
2. Which of the following is the correct syntax to format a Python dictionary data as a JSON string with indentation of 4 spaces?
easy
A. json.dumps(data, indent=4)
B. json.dumps(data, indent='4')
C. json.dumps(data, indent=True)
D. json.dumps(data, space=4)

Solution

  1. Step 1: Check the correct parameter type for indent

    The indent parameter expects an integer number of spaces, not a string or boolean.
  2. Step 2: Validate each option

    json.dumps(data, indent=4) uses indent=4 correctly. json.dumps(data, indent='4') uses a string '4' which is invalid. json.dumps(data, indent=True) uses boolean True which is invalid. json.dumps(data, space=4) uses a wrong parameter name space.
  3. Final Answer:

    json.dumps(data, indent=4) -> Option A
  4. Quick Check:

    Indent value must be integer [OK]
Hint: Use integer for indent, not string or boolean [OK]
Common Mistakes:
  • Passing indent as a string instead of integer
  • Using wrong parameter name like 'space'
  • Passing boolean instead of number
3. What is the output of this code?
import json
data = {'name': 'Alice', 'age': 30}
print(json.dumps(data, indent=2))
medium
A. {"name": "Alice", "age": 30}
B. { "name": "Alice", "age": 30 }
C. {name: Alice, age: 30}
D. SyntaxError

Solution

  1. Step 1: Understand json.dumps with indent=2

    The function converts the dictionary to a JSON string with 2 spaces indentation for each nested level.
  2. Step 2: Check the output format

    The output will have new lines and spaces, keys and string values in double quotes, and numeric values as is.
  3. Final Answer:

    { "name": "Alice", "age": 30 } -> Option B
  4. Quick Check:

    Indent=2 adds spaces and new lines [OK]
Hint: Indent adds new lines and spaces for readability [OK]
Common Mistakes:
  • Expecting compact JSON without spaces
  • Using single quotes instead of double quotes
  • Confusing Python dict print with JSON string
4. The following code throws an error. What is the mistake?
import json
data = {'x': 1, 'y': 2}
print(json.dumps(data, indent=2.0))
medium
A. json.dumps requires a second argument for separators
B. The data dictionary keys must be strings only
C. json.dumps cannot format dictionaries
D. The indent parameter should be an integer, not a float

Solution

  1. Step 1: Identify the error cause

    The indent parameter is given as a float 2.0 instead of an integer 2.
  2. Step 2: Understand parameter type requirements

    json.dumps expects indent to be an integer number of spaces for formatting, passing a float causes a TypeError.
  3. Final Answer:

    The indent parameter should be an integer, not a float -> Option D
  4. Quick Check:

    Indent must be int, not float [OK]
Hint: Check indent type: must be integer, not float [OK]
Common Mistakes:
  • Passing indent as float instead of int
  • Thinking keys must be strings for json.dumps
  • Expecting separators argument is mandatory
5. You have a list of dictionaries representing users:
users = [{'name': 'Bob', 'age': 25}, {'name': 'Eve', 'age': 28}]

How do you create a JSON string with indentation of 2 spaces and keys sorted alphabetically?
hard
A. json.dumps(users, indent='2', sort_keys=True)
B. json.dumps(users, indent=2, sort=True)
C. json.dumps(users, indent=2, sort_keys=True)
D. json.dumps(users, pretty=2, sort_keys=True)

Solution

  1. Step 1: Use json.dumps with indent and sort_keys

    The indent parameter formats the JSON with spaces and new lines. The sort_keys=True sorts dictionary keys alphabetically.
  2. Step 2: Validate correct parameter names and types

    json.dumps(users, indent=2, sort_keys=True) uses correct parameters and types. json.dumps(users, indent=2, sort=True) uses invalid parameter sort. json.dumps(users, indent='2', sort_keys=True) passes indent as string which is invalid. json.dumps(users, pretty=2, sort_keys=True) uses invalid parameter pretty.
  3. Final Answer:

    json.dumps(users, indent=2, sort_keys=True) -> Option C
  4. Quick Check:

    Use indent=int and sort_keys=True [OK]
Hint: Use sort_keys=True and indent as integer [OK]
Common Mistakes:
  • Using wrong parameter names like sort or pretty
  • Passing indent as string
  • Forgetting sort_keys to sort keys