Lists and dictionaries

I just started learning Python and i find it really easy to use although it gets me a bit confused when i have to use the %s/d/f in exercises.

prices = {
“banana” : 4,
“apple” : 2,
“orange” : 1.5,
“pear” : 3
}

stock = {
“banana” : 6,
“apple” : 0,
“orange” : 32,
“pear” : 15
}

for item in prices:
print item
print “price: %s” % prices[item]
print “stock: %s” % stock[item]

As in this code sequence for example I don’t really understand why i should use %s when the value corresponding to the key is an integer. ( the last two rows)

I guess you could use %d for integers and %f for floats.
%s is for strings,
but I guess Python can convert it if its not a string in this case.

prices = { "banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3 } stock = { "banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15 } for item in prices: print( item ) print( " price: %.2f" % prices[item] ) print( " stock: %d" % stock[item] )

[/quote]

1 Like

I see. I will try to use it in more situations like you did so that i can learn better. Thanks!