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

python – extract value from list of dictionary

I need to display book name and calculate average weight of book if the book price is more than 800.
here is my current code, appreciate any help. thank you so much in advance!

def calcWeight():
  for book in books:
    for key,value in book.items():
      if key == 'weight':
        if value >= 800:
        totalWeight += value
        avg = totalWeight / 2
        print(avg)

books = [{"name": "textbook", "weight": 500, "price": 800},
          {"name": "notebook", "weight": 100, "price": 200},
          {"name": "storybook", "weight": 700, "price": 1000}]

for book in books:
  for key,value in book.items():
    if key == 'price':
      if value >= 800:
        calcWeight()

>Solution :

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

books = [{"name": "textbook", "weight": 500, "price": 800},
          {"name": "notebook", "weight": 100, "price": 200},
          {"name": "storybook", "weight": 700, "price": 1000}]


total = 0
length = 0
for book in books:
    if book['price'] >= 800:
        total += book['weight']
        length += 1
        average = total / length
print(average)

You don’t need to loop, in a dictionary, though. In here, I’m assuming what you mean here is that you’re getting the average weight of the books if their price is greater than or equal to 800

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