Something of value trouble


#1



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 x in prices:
    total = prices * stock + total
    print total 

Oops, try again. Your code looks a bit off. Check the Hint if you need help! Your code threw the following error: unsupported operand type(s) for *: 'dict' and 'dict'

what is wrong with my code


#2

This can be initialized before the key in prices loop, then accumulated in that same loop.

We must multiply prices[item] by stock[item] so the values are evaluated.

    total += prices[item] * stock[item]
print total

Be sure to print the total outside of the loop.


#3

I am a little confused as to the exact purpose of the +=. Obviously simply using the = did not yield the correct answer, but why not? How does this sign work make it work?


#4

I should probably expand on my question.

using the code

for key in prices:
total = prices[key] * stock[key]

Wouldn't the loop make the keys for both prices and stock automatically perform the multiplication? Why would simply setting the total equal to that not work?


#5

+= is one of a group of special operators that make an assignment to an already defined variable that augments/decreases the value held. The operator cannot be used define a variable.

a = 0
a += 10
print a    # 10
a += 100
print a    # 110
a += 1000
print a    # 1110

The expression is the equivalent of,

a = a + 10

where we take the current value of a, add 10 and then assign the new amount back onto the original variable.

The other basic operations that can be performed in like manner, are,

-=
*=
/=
**=
//=
%=
  keys     prices  stock  extension
"banana" :   4       6       24
"apple"  :   2       0       0
"orange" :   1.5     32      48
"pear"   :   3       15      45
=================================
total =                      127

We cannot implicitly multiply two dicitionaries, but must cycle through each member and multiply their key values. The common keys is what makes this work.