Reputation: 11
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 ?!
Upvotes: 0
Views: 1373
Reputation: 11971
Assuming food is a list, you just need to change the for loop to:
for food_type in food:
total += prices[food_type]
Upvotes: 2