Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 }
like image 890
Rhys Isterix Avatar asked Apr 18 '13 15:04

Rhys Isterix


People also ask

How do you multiply the values of two dictionaries in python?

Use a dict comprehension to multiply two dictionaries in Python, e.g. result = {key: dict_1[key] * dict_2[key] for key in dict_1} . The dict comprehension iterates over the dictionary where we can multiply the value from one dict with the corresponding value from the other dict.


Video Answer


3 Answers

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
like image 182
DSM Avatar answered Nov 04 '22 02:11

DSM


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
like image 33
Abhijit Avatar answered Nov 04 '22 02:11

Abhijit


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   
like image 32
Alexander Petrov Avatar answered Nov 04 '22 01:11

Alexander Petrov