Using variables instead of numbers

Instead of getting the value from the dictionary and taking the number and adding it to health points … is there a way to use the key-value instead of just the value?

available_items = {"health potion": 10, "cake of the cure": 5, "green elixir": 20, "strength sandwich": 25, "stamina grains": 15, "power stew": 30}
health_points = 20
health_points += int("stamina grains")
available_items.pop("stamina grains",0)
health_points += 30
available_items.pop("power stew", 0)
health_points += 0
available_items.pop("mystic bread", 0)

print(available_items)
print(health_points)

Instead of adding 15 to health points I tried adding stamina points instead. This the error I got: ValueError: invalid literal for int() with base 10. Why do I get this error? Isn’t it basically a variable = value?

‘stamina grains’ is a string object that is a key in the available_items dictionary. So,

health_points += available_items["stamina grains"]

Not sure about how you are popping the dict items, but that should be able to raise an error now that we get past the line above.

Ok I see. It just raises a key error… So it’s not possible?

And as for the popping I am doing this excercise

Blockquote You are designing the video game Big Rock Adventure. We have provided a dictionary of items that are in the player’s inventory which add points to their health meter. In one line, add the corresponding value of the key "stamina grains" to the health_points variable and remove the item "stamina grains" from the dictionary. If the key does not exist, add 0 to health_points

The pop method returns the value for the popped key. We can furnish a default value to return if the key does not exist. That means we can combine two lines into one statement…

health_points += available_items["stamina grains"]
available_items.pop("stamina grains",0)

becomes,

health_points += available_items.pop("stamina grains",0)

That will add 15 if the key exists, and 0 if not, which is what the instruction asks for.

That worked! This makes sense. It produced a key error because a value was not returned?

Not exactly sure. POP will raise a KeyError if the key is missing and no default is supplied. We would need the exact traceback message to determine where the exception was raised.