[英]Accessing multiple data from Python dictionary
I have a Python dictionary that looks like this:我有一个看起来像这样的 Python 字典:
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).运行上面的代码会给我 300 的结果,因为它将字典中的前两个长度和宽度数据相乘 (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.同样,在我的用例中,会有数百个这样的“长度”和“宽度”数据条目。
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()
:
sum(item["length"] * item["breadth"] for item in data["dimensions"])
This outputs:这输出:
500
Passing a generator expression to sum
works nicely.将生成器表达式传递给sum
效果很好。
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. BrokenBenchmark 的答案效果很好,但是如果不需要临时区域列表,则使用生成器表达式与列表推导可以避免创建列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.