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 this 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? Again, in my use case, there would be hundreds of these "length" and "breadth" data entries.
CodePudding user response:
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
CodePudding user response:
Passing a generator expression to sum
works nicely.
sum(dim['length'] * dim['breadth'] for dim in data['dimensions'])
The answer by BrokenBenchmark works nicely, but if the interim list of areas is not necessary, using the generator expression vs. the list comprehension avoids the creation of a list.