python - Multiplying and then summing values from two dictionaries -


i need multiply values each key , add values print single number. know super simple i'm stuck

in mind, i'd address like:

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

but isn't going work :)

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

you use dict comprehension if wanted individuals:

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

or go straight total:

>>> sum(prices[k]*stock[k] k in prices) 117.0 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -