Question

New to Python. I am receiving an error and not sure how to fix it. AS you an see that I am using soem global variables in the function and initialized the dict to {} at the beginning of the program.

def bin_criticality():
    global gbv_bin_criticality, gbv_bin_element_ids, gbv_element_criticality
    gbv_bin_criticality = {}
    for (lv_key, lv_value) in gbv_bin_element_ids.items():
        print (lv_key, lv_value)
        lv_coil_ids = lv_value.split(',')
        for coil_id in lv_coil_ids:
            gbv_bin_criticality[lv_key] += int(gbv_element_criticality[coil_id])
    return()

----Error

line 112, in bin_criticality
    gbv_bin_criticality[lv_key] += int(gbv_element_criticality[coil_id])
KeyError: 0
Was it helpful?

Solution

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 globals - make gbv_bin_element_ids and gbv_element_criticality arguments to the function and return gbv_bin_criticality at the end.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top