Dictionary Values https://www.codecademy.com/courses/learn-python/lessons/a-day-at-the-supermarket/exercises/making-a-purchase

shopping_list = [“banana”, “orange”, “apple”]

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

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

Write your code below!

def compute_bill(food):
total=0
for stuff in food:
total += prices[stuff]
return total
print compute_bill(shopping_list)

This code runs the function correctly. My question is, how does the program know to only add the integers of this function. I keep thinking i have to specify greatly. For instance: it adds the values of apple, banana, and orange, but when building the function, I continue to think that I have to specify it to not add the string… Just looking for further clarity on dictionaries and their values/keys. Thank you

prices is the dictionaary of reference. We use the subscript to access the attribute which then gives us the value assigned to that attribute, hence, a number.

okay so if I were to just call prices, would it access the term and not the definition?
i.e. ‘prices[stuff]’ accesses 4(banana value), where as ‘prices’ would access banana?

We cannot echo the attribute name using the subscript syntax, only the value. To access the key(s) we can use for key in object or object.keys()

>>> for key in prices:
    print ('{}: {}'.format(key, prices[key]))

    
orange: 1.5
pear: 3
apple: 2
banana: 4
>>> 

OR

>>> print (list(prices.keys()))
['orange', 'pear', 'apple', 'banana']
>>> 

If we just print prices then we get the entire dictionary…

>>> print (prices)
{'orange': 1.5, 'pear': 3, 'apple': 2, 'banana': 4}
>>> 
1 Like

alright great thank you for all your time so far… so is .keys() a built in call in python?

1 Like

It is a built-in method of the dict class, yes. There is also another built-in, dict.values() which will retrieve all the values as a list object. To create a list of key-value pairs as tuples, use dict.items(). dict is the class, and would be replaced in this expression with the name of the dictionary.

prices.items()
1 Like