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

亡梦爱人 提交于 2019-11-28 07:52:37

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

If you would have known, how to iterate through a dictionary, index a dictionary using key and comprehend a dictionary, it would be a straight forward

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

Even if your implementation of Python does not provide Dictionary comprehension (< Py 2.7), you can pass it as a List Comprehension to the dict built-in

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

If you don;t want compatible between 2.X and 3.X you can also use iteritems instead of items

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

If you want a single total of the result, you can pass the individual products to sum

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

Correct answer for codeacademy according to task description:

 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   

I'm guessing you're on codeacademy? If so just do this:

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

Unlike what the instructions said you would have to add all the values together before multiplying them and adding them to total. Hope this helps.

I wrote the following code and it worked. for key in prices:

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

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

total = 0   
for key in prices:
    print prices[key] * stock[key]
    total += prices[key] * stock[key]
print total
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!