Unhashable type list?


#1



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


So I'm doing the compute a bill exercise, but I keep getting the "Oops, try again. compute_bill(['apple']) resulted in a TypeError: unhashable type: 'list' " message. I'm not sure how to correct this. Can anyone explain what is going on?


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
    for cost in food:
        cost = prices[food]
        total += cost
        return total


Sorry if it's obvious, but I can't find the answer for the life of me.


#2

Hi @coffeebeanie,

The function parameter, food, is meant to reference a list within a for loop. Since a list can be modified, a list cannot be used as a key to a dict object. prices is a dict.

Here, you are using food as a key ...

def compute_bill(food):
    total = 0
    for cost in food:
        cost = prices[food]

...
See the example code provided with this exercise regarding how to access individual items in a list. number is the variable that represents such items in the example code. You need to use individual items in the food list to access prices.


#3

Hi @coffeebeanie

In compute_bill function the "food" is a list contains more than one values. It can be converted seperately in "cost" in for loop.

for cost in food. Here cost indicates the particular single item in the list.

So,
cost=prices[food]
total+=cost
can be converted as

"total+=prices[cost]" and return statement is declared outside for loop.

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

Here prices[cost] indicates KEY of Shopping list of banana and refer the VALUE in prices dictionary of banana. Don't forget to call the function compute_bill with parameters shopping_list. (ie) print compute_bill(shopping_list)


#4

Thanks for the reply!


#5