Code Explanation:
1. Importing the json module
import json
The json module in Python allows us to work with JSON data.
It provides methods to serialize (convert Python objects → JSON string) and deserialize (convert JSON string → Python objects).
2. Creating a Python dictionary
data = {"a": 1, "b": 2}
Here, data is a dictionary with two key-value pairs:
"a": 1
"b": 2
3. Converting dictionary to JSON string
js = json.dumps(data)
json.dumps(data) converts the dictionary into a JSON-formatted string.
Example: {"a": 1, "b": 2} → '{"a": 1, "b": 2}' (notice it becomes a string).
4. Converting JSON string back to dictionary
parsed = json.loads(js)
json.loads(js) parses the JSON string back into a Python dictionary.
So parsed again becomes: {"a": 1, "b": 2}.
5. Adding a new key-value pair
parsed["c"] = parsed["a"] + parsed["b"]
A new key "c" is added to the dictionary.
Its value is computed as 1 + 2 = 3.
Now parsed = {"a": 1, "b": 2, "c": 3}.
6. Printing dictionary length and value
print(len(parsed), parsed.get("c", 0))
len(parsed) → counts number of keys in the dictionary = 3.
parsed.get("c", 0) → safely retrieves the value of "c". If "c" didn’t exist, it would return 0.
Here, "c" exists with value 3.
Final Output:
3 3
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment