Multiplication and subsequent summation of values โ€‹โ€‹from two dictionaries (prices, stocks)

I need to multiply the values โ€‹โ€‹from each key, and then add all the values โ€‹โ€‹together to print one number. I know this is probably very simple, but I'm stuck

In my opinion, I would address this with something like:

for v in prices:
total = sum(v * (v in stock))
print total

But something like this will not work :)

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

stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15 }
+3
source share
6 answers

You can use dict comprehension if you want people to:

>>> {k: prices[k]*stock[k] for k in prices}
{'orange': 48.0, 'pear': 45, 'banana': 24, 'apple': 0}

Or go straight to the bottom line:

>>> sum(prices[k]*stock[k] for k in prices)
117.0
+7
source

If you knew how to iterate through a dictionary, index the dictionary with a key, and understand the dictionary, this would be direct

>>> total = {key: price * stock[key] for key, price in prices.items()}
>>> total
{'orange': 48.0, 'pear': 45, 'banana': 24, 'apple': 0}

Python (< Py 2.7), dict

>>> dict((key, price * stock[key]) for key, price in prices.items())
{'orange': 48.0, 'pear': 45, 'banana': 24, 'apple': 0}

2.X 3.X, iteritems

{key: price * stock[key] for key, price in prices.iteritems()}

, sum

>>> sum(price * stock[key] for key, price in prices.items())
117.0
+2

, ? , :

total = 0
for key in prices:  
    prices = 53
    stock = 10.5
    total = prices + stock
print total  

, , , . , .

0

:

 prices = {
       "banana" : 4,
       "apple"  : 2,
       "orange" : 1.5,
       "pear"   : 3,
   }
   stock = {
        "banana" : 6,
        "apple"  : 0,
        "orange" : 32,
        "pear"   : 15,
    }

    for key in prices:
        print key
        print "price: %s" % prices[key]
        print "stock: %s" % stock[key]

     total = 0
     for key in prices:
        value = prices[key] * stock[key]
        print value
        total = total + value
    print total   
0

, . :

print key
   print "price: %s" % + prices[key]
   print "stock: %s" % + stock[key]

per key in prices: value = prices [key] * stock [key] print value total = total + value print total

0
source
total = 0   
for key in prices:
    print prices[key] * stock[key]
    total += prices[key] * stock[key]
print total
-1
source

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


All Articles