Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 a code to find the area:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading