Trying to access a dictionary key that does not exist will raise a KeyError
exception.
When trying to access or remove a key that may not be there, several solutions are possible:
- Use the
get()
method instead of a subscription. It will return None
for a missing key instead of raising a
KeyError
.
- Use the
setdefault()
method to provide keys that may be missing with a default value.
- Check that the key is present in the dictionary with the
if key in dict:
construct.
- Use a
try/except
block and handle the potential KeyError
exception.
- Use a
defaultdict
instead of a regular dict
object, and provide a default_factory
attribute.
Code examples
Noncompliant code example
def foo():
my_dict = {'k1': 42}
...
value = my_dict['k2'] # Noncompliant: the key "k2" does not exist.
Compliant solution
def foo():
my_dict = {'k1': 42}
...
if 'k2' in my_dict:
value = my_dict['k2']