Something of value - why [key] not [value]


#1


https://www.codecademy.com/en/courses/python-beginner-en-IZ9Ra/1/4?curriculum_id=4f89dab3d788890003000096

I already found a solution for the task but there is still one point that confuses me: Why would I use [key] in following code snippet when the numbers I want to add are actually the values in the dictionary (assuming i understood it correctly that the dictionary structure is dictionary = {key:value})?

total = prices[key] * stock[key] + total


I was trying to go with total = prices[value]*stock[value] + total
I feel like this describes better what I want to do. I want to multiply and add the values in my dictionary not the keys which are strings in this case. What would I do if I wanted to do something with the keys? How would I code that I really want to add the keys if they are numerals too?

Hope the question is clear and understandable.

Replace this line with your code. Do not remove the backticks that are above or below this line.


#2

lets take stock as example:

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

now python makes it really easy to loop over the keys:

for key in stock:
   print key

now key variable will hold the keys (banana, apple) and so on. So, now we have the key, if we want the value we can use the bracket notation to access the value at the key:

for key in stock:
    print stock[key]

Now we could combine this:

for key in stock:
    print "there are " + stock[key] + " " + key + "in stock"

Except then you have a int and a string, which is not so nice, so we can solve that:

for key in stock:
    print "there are " + str(stock[key]) + " " + key + " in stock"

or rather then concate we use comma's:

for key in stock:
    print "there are ",stock[key],key, "in stock"