Python收到KeyError:0

时间:2014-05-06 12:22:34

标签: python runtime-error

Python新手。我收到错误,不知道如何解决它。如你所见,我正在使用函数中的全局变量,并在程序开头将dict初始化为{}。

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()

----错误

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

1 个答案:

答案 0 :(得分:2)

gbv_bin_criticality在函数开头是一个空字典{},所以第一次尝试时:

gbv_bin_criticality[lv_key] += int(gbv_element_criticality[coil_id])

对于给定值lv_key,它还不存在作为字典中的键,因此KeyError

您有三个选项,先检查(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并优雅地失败(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])

或使用collections.defaultdict,它会自动处理丢失的密钥,而不是香草dict

from collections import defaultdict

gbv_bin_criticality = defaultdict(int)
...
gbv_bin_criticality[lv_key] += int(gbv_element_criticality[coil_id])

另外,我会放弃global s - 使gbv_bin_element_idsgbv_element_criticality参数到函数,并return gbv_bin_criticality在最后。