Code Explanation:
1. Importing the json Module
import json
Imports Python’s built-in json module.
This module allows you to parse JSON-formatted strings into Python objects (like lists and dictionaries).
2. JSON String as Input
data = '[{"a": 1}, {"a": 2}, {"a": 3}]'
data is a JSON-formatted string representing a list of dictionaries.
Each dictionary has a single key "a" with an integer value.
Equivalent Python object after parsing:
[{"a": 1}, {"a": 2}, {"a": 3}]
3. Defining the Generator Function
def extract_values(json_str):
This defines a function named extract_values that takes a JSON string as input.
It will yield (generate) values from the key 'a' in each dictionary.
4. Parsing and Iterating Over JSON Data
for obj in json.loads(json_str):
json.loads(json_str) converts the JSON string into a Python list of dictionaries.
The loop iterates over each dictionary (obj) in that list.
5. Yielding Values from Key 'a'
yield obj['a']
For each dictionary in the list, the function yields the value associated with the key 'a'.
So this yields: 1, then 2, then 3.
6. Calling the Function and Summing the Values
print(sum(extract_values(data)))
extract_values(data) returns a generator that yields 1, 2, 3.
sum(...) calculates the total sum of these values:
1 + 2 + 3 = 6
print(...) displays the result.
Output:
6
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment