Reputation: 291
Let's say buff is a dictionary. I do del buff[k]
, but k is not a key in the buff. Is this an error, or you python just passes the line like nothing happened?
Upvotes: 3
Views: 1479
Reputation: 140186
Let's test this:
>>> buff={1:2,4:5}
>>> del buff[1]
>>> del buff[6]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
KeyError: 6
Trying to delete a non-existing key of a dictionary with []
notation raises KeyError
Note that it's nicer to use buff.pop(k)
(in that case the delete operation triggers a KeyError
if doesn't exist, same outcome)
To create a non-crashing/fail-safe method just use pop
to remove and return a value (and in this case ignore the returned value):
if k in buff:
buff.pop(k)
or (better ask for forgiveness than permission):
try:
buff.pop(k)
except KeyError:
pass
or with a default value to avoid the exception:
buff.pop(k,None)
Upvotes: 4