Risky use of dict get method Low

Using the get method from the dict class without default values can cause undesirable results. Default parameter values can help prevent a KeyError exception.

Detector ID
python/dict-get-method@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1def keyerror_noncompliant():
2    mydict = {1: 1, 2: 2, 3: 3}
3    key = 5
4    try:
5        # Noncompliant: uses [] which causes exception when key is not found.
6        count = mydict[key]
7    except KeyError:
8        count = 0
9    return count

Compliant example

1def keyerror_compliant():
2    mydict = {1: 1, 2: 2, 3: 3}
3    key = 5
4    # Compliant: uses get() with a default value.
5    return mydict.get(key, 0)