Code Explanation
1. Importing the json Module
import json
The json module in Python is used for encoding (dumping) Python objects into JSON format and decoding (loading) JSON strings back into Python objects.
2. Creating a Dictionary
data = {"x": 5, "y": 10}
A dictionary data is created with two keys:
"x" mapped to 5
"y" mapped to 10.
3. Converting Dictionary to JSON String
js = json.dumps(data)
json.dumps(data) converts the Python dictionary into a JSON-formatted string.
Now, js = '{"x": 5, "y": 10}'.
4. Converting JSON String Back to Dictionary
parsed = json.loads(js)
json.loads(js) parses the JSON string back into a Python dictionary.
Now, parsed = {"x": 5, "y": 10}.
5. Adding a New Key to Dictionary
parsed["z"] = parsed["x"] * parsed["y"]
A new key "z" is added to the dictionary parsed.
Its value is the product of "x" and "y" → 5 * 10 = 50.
Now, parsed = {"x": 5, "y": 10, "z": 50}.
6. Printing Dictionary Length and Value
print(len(parsed), parsed["z"])
len(parsed) → number of keys in the dictionary → 3 ("x", "y", "z").
parsed["z"] → value of key "z" → 50.
Output:
3 50
Final Output
3 50
.png)

0 Comments:
Post a Comment