this works:
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def compute_bill(food):
total = 0
# food = tuple(food)
for food in food:
total += prices[food]
return total
print compute_bill(shopping_list)
But if I change food to anything else in the loop, for example X - for x in food - then python gives me below error (it only works with for food in food.)
Traceback (most recent call last):
File "compute-shopping.py", line 25, in <module>
print compute_bill(shopping_list)
File "compute-shopping.py", line 21, in compute_bill
total += prices[food]
TypeError: unhashable type: 'list'
This is not related to using tuple or list as key for dictionary ... or is it ?!
foodas you are overwriting the earlier value offoodfor food in foodhave you considered referring to its contents by a different name?fooda list or a string? Python seems to think it's a list, and you are using it to index a dictionary, which is a no-no. Dictionary keys must be immutable.foodare you changing?