Code Explanation:
Import the json module
import json
This imports Python’s json module.
It allows converting between Python objects and JSON (JavaScript Object Notation) strings.
Common functions:
json.dumps() → Python → JSON string
json.loads() → JSON string → Python object
Create a dictionary
data = {"x": 3, "y": 4}
A Python dictionary named data is created.
It contains two key-value pairs:
'x': 3
'y': 4
Now data = {'x': 3, 'y': 4}
Convert dictionary to JSON string
js = json.dumps(data)
json.dumps() converts the Python dictionary data into a JSON-formatted string.
So now,
js = '{"x": 3, "y": 4}'
This is a string, not a Python dictionary.
Convert JSON string back to dictionary
parsed = json.loads(js)
json.loads() converts the JSON string js back into a Python dictionary.
Now parsed = {'x': 3, 'y': 4}
Add a new key-value pair
parsed["z"] = parsed["x"] * parsed["y"]
A new key 'z' is added to the dictionary.
The value is calculated by multiplying 'x' and 'y':
→ 3 * 4 = 12
Now parsed becomes:
{'x': 3, 'y': 4, 'z': 12}
Print dictionary information
print(len(parsed), parsed["z"])
len(parsed) → number of keys in the dictionary = 3
parsed["z"] → value of 'z' = 12
Final Output
3 12
.png)

0 Comments:
Post a Comment