如果dict键不存在或为零?

2024-10-01 11:25:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想确定dict key的值处于以下哪种状态:

  1. 不存在
  2. 存在,但等于0的整数
  3. 存在,并且等于大于0的整数

以下是我目前正在尝试的:

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不在itemdict中时,我在if item[itemTo] == 0:行得到这个错误:

^{pr2}$

Tags: ofkeyyouif状态have整数item
1条回答
网友
1楼 · 发布于 2024-10-01 11:25:14

要更改测试顺序:

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

相关问题 更多 >