Ninja Bug
Ninja Bug

Reputation: 291

What happens if I delete a nonexistent key in Python Dictionary Class?

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

Answers (1)

Jean-François Fabre
Jean-François Fabre

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

Related Questions