为什么 python dict 出现 KeyError 但 Key 存在?

问题描述 投票:0回答:1

代码:

for targetMetric in targetMetricArr:
    print(targetMetric)
    print(valueDict[curEndPoint].keys())
    try:
        print(len(valueDict[curEndpoint][targetMetric]))
    except:
        print('exception happen')
        print(targetMetric in valueDict[curEndPoint])
        print(valueDict[curEndPoint].keys())

输出:

perf.metric.memory.latency/cpu_vendor=common,unit=ns
dict_keys(['perf.metric.memory.bandwidth_total/cpu_vendor=common,unit=mb/s', 'perf.metric.cpu.utilization/cpu_vendor=common,unit=percentage', 'perf.metric.memory.bandwidth_max/cpu_vendor=common,unit=mb/s', 'perf.metric.memory.latency/cpu_vendor=common,unit=ns', 'cpu.busy'])
exception happen
True
dict_keys(['perf.metric.memory.bandwidth_total/cpu_vendor=common,unit=mb/s', 'perf.metric.cpu.utilization/cpu_vendor=common,unit=percentage', 'perf.metric.memory.bandwidth_max/cpu_vendor=common,unit=mb/s', 'perf.metric.memory.latency/cpu_vendor=common,unit=ns', 'cpu.busy'])

可以看到,查找到的key在

valueDict[curEndPoint]
字典中是存在的,但是还是出现异常。 这是什么原因?

我正在使用Python 3.11.5

python dictionary keyerror
1个回答
0
投票

看起来这只是一个名称错误,关键变量名称是

curEndpoint
而不是
curEndPoint
。作为参考,您不应使用一揽子
except
来涵盖所有异常,因为您无法获得有关错误类型和消息的大量上下文。最好使用
except <Error type> as ex
为不同的错误类型设置多个例外,然后您可以使用
str(ex)

获取错误消息
targetMetricArr = ['perf.metric.memory.latency/cpu_vendor=common,unit=ns']

valueDict = {
    'curEndPoint': {
        'perf.metric.memory.latency/cpu_vendor=common,unit=ns': True,
        'perf.metric.memory.bandwidth_total/cpu_vendor=common,unit=mb/s': True,
        'cpu.busy': True
    }
}

curEndPoint = 'curEndPoint'

for targetMetric in targetMetricArr:
    print(targetMetric)
    print(valueDict[curEndPoint].keys())
    try:
        print(len(valueDict[curEndpoint][targetMetric]))
    except NameError as ex:
        print('NameError exception happen:', str(ex))
        print(targetMetric in valueDict[curEndPoint])
        print(valueDict[curEndPoint].keys())
    except ValueError as ex:
        print('ValueError exception happen:', str(ex))
        print(targetMetric in valueDict[curEndPoint])
        print(valueDict[curEndPoint].keys())

© www.soinside.com 2019 - 2024. All rights reserved.