What happens if I delete a non-existent key in the Python dictionary class?… here is a solution to the problem.
What happens if I delete a non-existent key in the Python dictionary class?
Suppose buff is a dictionary. I execute del buff[k], but k is not a key in buff
. Is this a bug, or is your python just passing the line like nothing happened?
Solution
Let’s test it:
>>> 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
But in this case, del
has nothing to do with it. Using the []
symbol to access a key that does not exist in the dictionary throws a KeyError
Note that it is better to use buff.pop(k) (
in this case, the delete operation triggers KeyError
, the result is the same if it does not exist).
To create a method that doesn’t crash/fail-safe, simply do the following:
if k in buff:
buff.pop(k)
Or (it’s better to ask for forgiveness than for permission):
try:
buff.pop(k)
except KeyError:
pass