42 lines
1.1 KiB
Plaintext
42 lines
1.1 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Trying to access a dictionary key that does not exist will raise a `KeyError`.
|
|
|
|
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`.
|
|
* Use a `defaultdict` instead of a regular `dict` object.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,python]
|
|
----
|
|
def foo():
|
|
my_dict = {'k1': 42}
|
|
...
|
|
value = my_dict['k2'] # Noncompliant
|
|
----
|
|
=== Compliant solution
|
|
|
|
[source,python]
|
|
----
|
|
def foo():
|
|
my_dict = {'k1': 42}
|
|
...
|
|
if 'k2' in my_dict:
|
|
value = my_dict['k2']
|
|
----
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
'''
|
|
endif::env-github,rspecator-view[] |