Home > Enterprise >  python - extract value from list of dictionary
python - extract value from list of dictionary

Time:10-26

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()

CodePudding user response:

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

CodePudding user response:

Here is one way that you can do what you want:

def calcWeight(books):
    filtered_elements = [book['weight'] for book in books if book['price'] >= 800] # create a list full of weights for those over the price limit
    return sum(filtered_elements) / len(filtered_elements) # returns the average of all weighted books

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

average_weight = calcWeight(books) # store the value from the function
for book in books:
    if book['price'] >= 800: # grab the value from the dictionary and see if it meets our condition
        print(book['name'], average_weight) # print out the name and average 

CodePudding user response:

Use pandas to create a DataFrame

import pandas as pd

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

df = pd.DataFrame(books)

Then filter for pricy books:

df_pricy = df[df.price>800]

Then analyse data:

names = list(df_pricy.name)
average_weight = df_pricy.weight.mean()

print("Pricy Books:",names)
print("Average Weight of pricy books",average_weight)
  • Related