0
0
Pythonprogramming~10 mins

Formatting structured data in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to convert the dictionary to a JSON string.

Python
import json

person = {"name": "Alice", "age": 30}
json_str = json.[1](person)
print(json_str)
Drag options to blanks, or click blank then click option'
Adumps
Bloads
Cload
Ddump
Attempts:
3 left
💡 Hint
Common Mistakes
Using json.load or json.loads instead of json.dumps
Confusing dump and dumps functions
2fill in blank
medium

Complete the code to pretty-print the JSON string with indentation.

Python
import json

data = {"city": "Paris", "population": 2148327}
pretty_json = json.dumps(data, [1]=4)
print(pretty_json)
Drag options to blanks, or click blank then click option'
Aensure_ascii
Bsort_keys
Cseparators
Dindent
Attempts:
3 left
💡 Hint
Common Mistakes
Using sort_keys instead of indent
Forgetting to set indent to a number
3fill in blank
hard

Fix the error in the code to load JSON data from a string.

Python
import json

json_data = '{"fruit": "apple", "count": 10}'
data = json.[1](json_data)
print(data)
Drag options to blanks, or click blank then click option'
Aloads
Bdumps
Cload
Ddump
Attempts:
3 left
💡 Hint
Common Mistakes
Using json.load instead of json.loads
Using json.dumps or json.dump which write JSON
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.

Python
words = ["apple", "bat", "cat", "door"]
lengths = {word: [1] for word in words if [2] > 3}
print(lengths)
Drag options to blanks, or click blank then click option'
Alen(word)
Bword
Attempts:
3 left
💡 Hint
Common Mistakes
Using the word itself as the value instead of its length
Checking the word instead of its length in the condition
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase words to their counts only if count is positive.

Python
counts = {"apple": 2, "banana": 0, "cherry": 5}
result = { [1]: [2] for [3], count in counts.items() if count > 0 }
print(result)
Drag options to blanks, or click blank then click option'
Aword.upper()
Bcount
Cword
Dfruit
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names in the loop
Not converting the word to uppercase for the key