gbv_bin_criticality
is an empty dictionary {}
at the start of the function, so the first time you try:
gbv_bin_criticality[lv_key] += int(gbv_element_criticality[coil_id])
for a given value of lv_key
it doesn't yet exist as a key in the dictionary, hence KeyError
.
You have three options, either check first (LBYL):
if lv_key not in gbv_bin_criticality:
gbv_bin_criticality[lv_key] = 0
gbv_bin_criticality[lv_key] += int(gbv_element_criticality[coil_id])
try
and fail gracefully (EAFP):
try:
gbv_bin_criticality[lv_key] += int(gbv_element_criticality[coil_id])
except KeyError:
gbv_bin_criticality[lv_key] = int(gbv_element_criticality[coil_id])
or use collections.defaultdict
, which will automatically handle the missing key, instead of the vanilla dict
:
from collections import defaultdict
gbv_bin_criticality = defaultdict(int)
...
gbv_bin_criticality[lv_key] += int(gbv_element_criticality[coil_id])
Also, I would ditch the global
s - make gbv_bin_element_ids
and gbv_element_criticality
arguments to the function and return gbv_bin_criticality
at the end.