If dict key doesn't exist or is zero?

dictionary, python

Solution

You want to change the order of the tests:

if itemTo not in item:
    print("%s doesn't exist." % (itemTo))
elif item[itemTo] > 0:
    print("You have %i of %s." % (item[itemTo]))
else:
    print("You don't have a %s." % (itemTo))

Problem

I'd like to determine which of the following states a dict key's value is in: - Doesn't exist - Exists, but is equal to an int of 0 - Exists, and is equal to an int greater than 0 Here's what I'm currently trying: ``` if item[itemTo] == 0: print("You don't have a %s." % (itemTo)) elif item[itemTo] > 0: print("You have %i of %s." % (item[itemTo])) else: print("%s doesn't exist." % (itemTo)) ``` But, when `itemTo` isn't in the `item` dict, I get this error at the line `if item[itemTo] == 0:`: ``` KeyError: 'whatever_value_of_itemTo' ```

Original source