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 returnNonefor a missing key instead of raising aKeyError.
-  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/exceptblock and handle the potentialKeyErrorexception.
-  Use a defaultdictinstead of a regulardictobject, and provide adefault_factoryattribute.
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']