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 }
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With