简体   繁体   中英

Accessing multiple data from Python dictionary

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM