Using the get
method from the dict
class without default values can cause undesirable results. Default parameter values can help prevent a KeyError
exception.
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
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)