Question: Question:
I use del to remove a key from a dict in Python, but I get a KeyError if the key I'm trying to remove doesn't exist.
>>> a = dict(a=1, b=2)
>>> del a["c"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'
In order to avoid this, it is necessary to check in advance whether the key exists as shown below.
>>> a = dict(a=1, b=2)
>>> if "c" in a:
... del a["c"]
...
>>>
Is there an easier way to write to remove a key that may not exist?
Answer: Answer:
Use dict.pop
a = dict(a=1, b=2)
a.pop('c', None) # None
print a # {'a': 1, 'b': 2}
a.pop('a', None) # 1
print a # {'b': 2}
If
key
is in the dictionary, remove it and return its value, else returndefault
. Ifdefault
is not given and key is not in the dictionary, a KeyError is raised.
pop(key[, default])
removes the key from the dictionary and returns the value of the element, or default
. If you don't pass the second argument default
when popping an pop
key, you'll get a KeyError
. You can specify it with None
as in the above example.