如果dict键不存在或为零?

时间:2012-12-04 00:08:10

标签: python dictionary

我想确定dict键值的下列哪个状态:

  1. 不存在
  2. 存在,但等于0
  3. 的int
  4. 存在,等于大于0的int
  5. 以下是我正在尝试的内容:

    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))
    

    但是,如果itemTo不在item字典中,我会在第if item[itemTo] == 0:行收到此错误:

    KeyError: 'whatever_value_of_itemTo'
    

1 个答案:

答案 0 :(得分:7)

您想要更改测试的顺序:

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))