Determine the value of items in one dictionary based on prices in another

Here I have a program that gives the total cost of individual products, multiplying prices and stocks. But what should I use to find the total value of all products combined?

total = 0
prices = {
    "banana" : 4,
    "apple" : 2,
    "orange" : 1.5,
    "pear" : 3
}

stock = {
    "banana" : 9,
    "apple" : 0,
    "orange" : 18,
    "pear" : 22
}

for i in prices:
    print (i.title())
    print ("Price:", prices[i])
    print ("Stock:", stock[i])
    print ("=================")

for key in prices:
    print(key.title() + " Total Price:" , prices[key]*stock[key])
+4
source share
2 answers

sum(prices[key] * stock[key] for key in prices)

+3
source

Assuming that you mean the total number of all items in the warehouse, you can store the totals in a structure that will be easily disabled later, providing easy manipulation:

totals = {k:(stock[k] * prices[k]) for k in prices if k in stock}

In [12]: sum(totals.values())
Out[12]: 129.0
+1
source

Source: https://habr.com/ru/post/1627212/


All Articles