Something of value confusion


I got the exercise right with help but confused by the use of this code:print "price: %s" % prices[key]
print "stock: %s" % stock[key]
memory's a bit rough of the previous exercises so an explanation would help.

Thanks in advance.

prices = {
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,

total = 0
for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]
    total += prices[key] * stock[key]
print total


I believe this is called modulo formatting.

"string with %args" % kwargs

Inside the string, the modulo arguments are,

%s  => string object expected in keyword arguments

%i  => integer object expected in kwargs

%d  => double precision integer expected in kwargs

%f  => float object expected in kwargs

%r  => representation object (list, dictionary) expected in kwargs

This is not an exhaustive list but the most common types expressed.


Sorry to say but I'm still not getting it :confused:
Because as the instruction says: Loop through the prices dictionaries.
For each key in prices, multiply the number in prices by the number in stock. Print that value into the console and then add it to total.
Doesn't make sense with the code for me.


I'm not sure where the confusion is. Your code is correct so you must have some idea, unless the code is copied and you are just trying to understand it.


the instruction gave a similar code so I just replaced some words and it worked so I kind of also need to understand it if you are willing to explain.


Let's start with the above line. Do you understand what this line is doing?

dots for the sake of 20 characters :£


So we are iterating over a dictionary which has keys in common with another dictionary.

total = 0
for key in prices and stock:   # legitimate way to show both dictionaries
    print key                  # prints one of, banana, pear, apple, or orange
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]
    total += prices[key] * stock[key]
print total

Given key is banana, the output will be,

price: 4
stock: 6

total will now read 24 when we add 4 * 6.

"string content %s" % variable
                 ^        ^
                 |        |
         placeholder for  |
                        this guy


Really helpful, thanks.


so in conclusion basically %s' job is to be a placeholder ?


That is correct. See the earlier post for the various descriptors denoting expected data type.