Code Explanation:
1. Importing the json library
import json
We import the built-in json module.
This module helps us convert between Python objects and JSON strings.
2. Creating a dictionary
data = {"p": 2, "q": 5}
A dictionary data is created with two keys:
"p" → value 2
"q" → value 5.
3. Converting dictionary to JSON string
js = json.dumps(data)
json.dumps() converts the Python dictionary into a JSON formatted string.
Example: {"p": 2, "q": 5} becomes '{"p": 2, "q": 5}'.
4. Parsing JSON back to Python dictionary
parsed = json.loads(js)
json.loads() takes the JSON string js and converts it back into a Python dictionary.
Now, parsed is again: {"p": 2, "q": 5}.
5. Adding a new key-value pair
parsed["r"] = parsed["p"] ** parsed["q"]
parsed["p"] is 2, and parsed["q"] is 5.
2 ** 5 = 32.
So, a new key "r" is added with value 32.
Final dictionary: {"p": 2, "q": 5, "r": 32}.
6. Printing the results
print(len(parsed), parsed["r"])
len(parsed) → there are 3 keys in the dictionary (p, q, r).
parsed["r"] → value is 32.
Output:
3 32


0 Comments:
Post a Comment