我想确定dict键值的下列哪个状态:
以下是我正在尝试的内容:
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'
答案 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))