Code Explanation:
1. Importing the Module
import json
We import the json module from Python’s standard library.
This module is used for working with JSON (JavaScript Object Notation) data.
Functions like json.dumps() and json.loads() help convert between Python objects and JSON strings.
2. Creating a Python Dictionary
data = {"a": 2, "b": 3}
A dictionary data is created with two key-value pairs:
"a": 2
"b": 3
3. Converting Dictionary to JSON String
js = json.dumps(data)
json.dumps(data) converts the Python dictionary into a JSON formatted string.
Example: {"a": 2, "b": 3} → '{"a": 2, "b": 3}' (notice it becomes a string).
4. Parsing JSON String Back to Dictionary
parsed = json.loads(js)
json.loads(js) converts the JSON string back into a Python dictionary.
Now parsed = {"a": 2, "b": 3} again (but it’s reconstructed).
5. Adding a New Key to Dictionary
parsed["c"] = parsed["a"] * parsed["b"]
A new key "c" is added to the dictionary.
Its value is the product of "a" and "b".
Calculation: 2 * 3 = 6.
Now dictionary = {"a": 2, "b": 3, "c": 6}.
6. Printing the Results
print(len(parsed), parsed["c"])
len(parsed) → Counts the number of keys in the dictionary → 3.
parsed["c"] → Fetches value of "c" → 6.
Output = 3 6.
Final Output:
3 6
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment