Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

python - Multiplying and then summing values from two dictionaries (prices, stock)

I need to multiply the values from each key and then add all the values together to print a single number. I know this probably super simple but i'm stuck

In my mind, I'd address this with something like:

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

But something like that isn't going to work :)

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

stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use a dict comprehension if you wanted the individuals:

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

Or go straight to the total:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...