Formatting structured data in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we format structured data, like turning a list or dictionary into a string, the time it takes depends on how much data we have.
We want to know how the work grows as the data gets bigger.
Analyze the time complexity of the following code snippet.
def format_data(data):
result = ""
for key, value in data.items():
result += f"{key}: {value}\n"
return result
This code takes a dictionary and creates a string with each key and value on its own line.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each key-value pair in the dictionary.
- How many times: Once for every item in the dictionary.
As the number of items grows, the work grows in a similar way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loops and string additions |
| 100 | About 100 loops and string additions |
| 1000 | About 1000 loops and string additions |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n^2)
This means the time to format the data grows quadratically with the number of items due to string concatenation in a loop.
[X] Wrong: "Formatting data is always super fast and doesn't depend on size."
[OK] Correct: Actually, the more items you have, the more work the program must do to format each one, so time grows with size.
Understanding how formatting time grows helps you explain how programs handle bigger data smoothly and why efficiency matters.
"What if we used a list of tuples instead of a dictionary? How would the time complexity change?"
Practice
indent parameter do in json.dumps() when formatting structured data?Solution
Step 1: Understand the purpose of
This function converts Python data into a JSON string.json.dumps()Step 2: Role of
Theindentparameterindentparameter adds spaces and new lines to format the JSON string nicely for readability.Final Answer:
Adds spaces and new lines to make the output easier to read -> Option AQuick Check:
indent= readable JSON [OK]
- Thinking indent compresses JSON
- Confusing indent with encryption
- Assuming indent changes data content
data as a JSON string with indentation of 4 spaces?Solution
Step 1: Check the correct parameter type for indent
Theindentparameter expects an integer number of spaces, not a string or boolean.Step 2: Validate each option
json.dumps(data, indent=4) usesindent=4correctly. 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 namespace.Final Answer:
json.dumps(data, indent=4) -> Option AQuick Check:
Indent value must be integer [OK]
- Passing indent as a string instead of integer
- Using wrong parameter name like 'space'
- Passing boolean instead of number
import json
data = {'name': 'Alice', 'age': 30}
print(json.dumps(data, indent=2))Solution
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.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.Final Answer:
{ "name": "Alice", "age": 30 } -> Option BQuick Check:
Indent=2 adds spaces and new lines [OK]
- Expecting compact JSON without spaces
- Using single quotes instead of double quotes
- Confusing Python dict print with JSON string
import json
data = {'x': 1, 'y': 2}
print(json.dumps(data, indent=2.0))Solution
Step 1: Identify the error cause
Theindentparameter is given as a float 2.0 instead of an integer 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.Final Answer:
The indent parameter should be an integer, not a float -> Option DQuick Check:
Indent must be int, not float [OK]
- Passing indent as float instead of int
- Thinking keys must be strings for json.dumps
- Expecting separators argument is mandatory
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?
Solution
Step 1: Use json.dumps with indent and sort_keys
Theindentparameter formats the JSON with spaces and new lines. Thesort_keys=Truesorts dictionary keys alphabetically.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 parametersort. 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 parameterpretty.Final Answer:
json.dumps(users, indent=2, sort_keys=True) -> Option CQuick Check:
Use indent=int and sort_keys=True [OK]
- Using wrong parameter names like sort or pretty
- Passing indent as string
- Forgetting sort_keys to sort keys
