0

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 ?!

7
  • 2
    Please change the loop variable to something other than food as you are overwriting the earlier value of food Commented Sep 4, 2015 at 21:07
  • for food in food have you considered referring to its contents by a different name? Commented Sep 4, 2015 at 21:09
  • Is food a 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. Commented Sep 4, 2015 at 21:12
  • 1
    What do you mean by "change food to anything else"? What are the possible values of "anything else"? And what instance of food are you changing? Commented Sep 4, 2015 at 21:12
  • if I change food to foot_type or any other variable name, I get ' unhashable type: 'list' ; so the question is why For food in food loop only work and not For food_type in food ? or for x in food ? Commented Sep 5, 2015 at 8:38

1 Answer 1

2

Assuming food is a list, you just need to change the for loop to:

for food_type in food:
    total += prices[food_type]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.