I have a Python dictionary that looks like this:
data = {
"shape" : "rectangle",
"dimensions" : [ {
"length" : 15,
"breadth": 20
}, {
"length" : 20,
"breadth": 10
} ]
}
In my use case, there would be over one hundred of these rectangles with their dimensions.
I wrote a code to find the area:
length = data['dimensions'][0]['length']
breadth = data['dimensions'][0]['breadth']
area = length * breadth
print(area)
Running the code above will give me the result of 300 because it multiplies the first two length and breadth data from the dictionary (15 * 20).
How do I also get the multiplied value of the other "length" and "breadth" data and add them together with a loop of some sort? because again, in my use case there would be hundreds of these "length" and "breadth" data.
>Solution :
You can use a list comprehension:
[item["length"] * item["breadth"] for item in data["dimensions"]]
This outputs:
[300, 200]
To sum them, you can use sum():
sum(item["length"] * item["breadth"] for item in data["dimensions"])
This outputs:
500