简体   繁体   中英

Create a sum of specific values in a dict in Python

I have this dict with my values for some products which can be added to the cart. I want to sum the prices of all products in the cart and print them. How Do I select the specific value (price) from the dict using a function. In this instance ShoeA should be two times in the cart which should result in 144.98 + 144.98 = 289.96

Here is my complete code:

shoeA = {"id": 342453, "name": "Shoe A", "price": 144.98 }
shoeB = {"id": 9800989, "name": "Shoe B", "price": 300}

# A cart of a shop has the following functions. Each functionality should be implemented as a separate function.
# 1.1 add_product(cart, product, times): adds a product "times" times to the cart. The cart is a list and the product a
# dictionary. A product consists of a ID, name and price

cart = []
def add_product(product, times):
    for i in range(0, times):
        cart.append(product)
    print(cart)
add_product(342453, 4)

# 1.2 remove_product(cart, productID): Removes all products with ID = productID from the given cart
# 1.3 print_cart(cart): Prints the whole cart
def remove_product(productID, times):
    for i in range(0, times):
        cart.remove(productID)
    print(cart)
remove_product(342453, 2) #only two reductions.

# 1.4 find_product(cart, productID): Returns a list of integers, which are indexes of the searched product in the cart.
# E.g. find_product(cart, 12) may return [2,5,10] if the cart contains a the product with productID at index 2,5 and 10.
def find_product(productID):
    for i, j in enumerate(cart):
        if j == productID:
            print(i)
find_product(342453)

# 1.5 get_total(cart): Function that sums up the prices of all products in the cart and returns this value
def get_total():
    #Please help me here. :)
get_total()

First, you'll need somewhere to keep a catalog of the products, like so:

catalog = [shoeA, shoeB]

Then, you can use a simple for-loop to find the sum of the products:

def total_price():
  sum = 0
  for product in catalog:
    sum += product['price'] * cart.count(product['id'])
  return sum

Firstly, you have to store all products in a list or dict.

all_products = {342453: shoeA, 9800989: shoeB}

Then simply iterate over it and add up all the prices.

def get_total():
    total = 0
    for productId in cart:
        shoe = all_products[productId]
        total += shoe["price"]
    print("Total: ", total)

Here's the Complete code:

shoeA = {"id": 342453, "name": "Shoe A", "price": 144.98 }
shoeB = {"id": 9800989, "name": "Shoe B", "price": 300}

# A cart of a shop has the following functions. Each functionality should be implemented as a separate function.
# 1.1 add_product(cart, product, times): adds a product "times" times to the cart. The cart is a list and the product a
# dictionary. A product consists of a ID, name and price

all_products = {342453: shoeA, 9800989: shoeB}
cart = []


def add_product(product, times):
    for i in range(0, times):
        cart.append(product)
    print(cart)
add_product(342453, 4)

# 1.2 remove_product(cart, productID): Removes all products with ID = productID from the given cart
# 1.3 print_cart(cart): Prints the whole cart
def remove_product(productID, times):
    for i in range(0, times):
        cart.remove(productID)
    print(cart)
remove_product(342453, 2) #only two reductions.

# 1.4 find_product(cart, productID): Returns a list of integers, which are indexes of the searched product in the cart.
# E.g. find_product(cart, 12) may return [2,5,10] if the cart contains a the product with productID at index 2,5 and 10.
def find_product(productID):
    for i, j in enumerate(cart):
        if j == productID:
            print(i)
# find_product(342453)

# 1.5 get_total(cart): Function that sums up the prices of all products in the cart and returns this value
def get_total():
    total = 0
    for productId in cart:
        shoe = all_products[productId]
        total += shoe["price"]
    print("Total: ", total)

get_total()

Change the declaration of the shoe products into a dictionary of products. I updated the other functions to reflect that change.

products_dict = {342453 : {"name": "Shoe A", "price": 144.98 }, 9800989: {"name": "Shoe B", "price": 300}}

# A cart of a shop has the following functions. Each functionality should be implemented as a separate function.
# 1.1 add_product(cart, product, times): adds a product "times" times to the cart. The cart is a list and the product a
# dictionary. A product consists of a ID, name and price

cart = []
def add_product(product_id, times):
    for i in range(0, times):
        cart.append(products_dict[product_id])
    print(cart)
add_product(342453, 4)

# 1.2 remove_product(cart, productID): Removes all products with ID = productID from the given cart
# 1.3 print_cart(cart): Prints the whole cart
def remove_product(product_id, times):
    for i in range(0, times):
        cart.remove(products_dict[product_id])
    print(cart)
remove_product(342453, 2) #only two reductions.

# 1.4 find_product(cart, productID): Returns a list of integers, which are indexes of the searched product in the cart.
# E.g. find_product(cart, 12) may return [2,5,10] if the cart contains a the product with productID at index 2,5 and 10.
def find_product(product_id):
    for index, product in enumerate(cart):
        if product == products_dict[product_id]:
            print(index)
find_product(342453)

# 1.5 get_total(cart): Function that sums up the prices of all products in the cart and returns this value
def get_total():
    #Please help me here. :)
    sum = 0
    for product in cart:
        sum += product["price"]
    print(sum)
get_total()

I would suggest to first try a easier-to-manage structure of your products. Like a nested dictionary

catalog = dict(
    shoeA={"id": 342453, "name": "Shoe A", "price": 144.98 },
    shoeB={"id": 9800989, "name": "Shoe B", "price": 300} 
)

This means that the whole catalog will be callable. The problem with your code is that each product is separated thus not easily callable. In the nested dictionary we can easily call the product variable since it is just considered a string.

Then you edit the add function to accommodate not the internal details of your product (which is the case in your code) but the 'catalog' key(product) instead. Future functions should call this key (eg 'shoeA', or 'shoeB')

cart = []
cart_id = []
def add_product(product, times):
    for i in range(0, times):
        cart.append(product)
        cart_id.append(catalog[product]['id'])
    print(cart)
    print(cart_id)
add_product('shoeA', 4)

['shoeA', 'shoeA', 'shoeA', 'shoeA']
[342453, 342453, 342453, 342453]

In this part we used the callable nested dictionary. Now you have free control of all attributes of the product you want easily. For example, if you want to retain the list of ids you can use the cart_id instead of the cart.

Now this format makes it easy to do a sum.

def get_total():
    cart_prices = [catalog[product]['price'] for product in cart ]
    total = sum(cart_prices)
    print(cart_prices)
    print(total)
get_total()

This should work. Feel free to adjust the other functions to accept the new structure.

To process the extracted products data ( documents, api or database ) you could store them in this way if they have a fixed and available size:

product_dict = {product["id"]:product for product in products}

Then iterate over cart list like this to return a total sum:

def get_total():
     amount = 0
     for product_id in set(cart):
         amount += product_dict[product_id]["price"] * cart.count(product_id)
   return amount

print(get_total()) 

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