Python嵌套字典按feature取throughput值,不存在返回NA的问题
问题
现有嵌套字典results,顶层键为IPSEC-IMIX这类特征标识。需要根据字符串变量the_feature获取对应子字典的throughput值;若特征不存在则返回"NA"。
尝试以下代码时,当the_feature不存在会抛出KeyError错误:
answer = results[the_feature]["throughput"] if results[the_feature]["throughput"] else "NA"
错误信息:
Traceback (most recent call last): File "C:\code\api_server_imix.py", line 1113, in get_results item["release_speed"] = release_obj.results[the_feature].get("throughput", "NA") value = super().__getitem__(key) ^^^^^^^^^^^^^^^^^^^^^^^^ KeyError: 'IPSEC-1400'
解决方案
推荐使用两次dict.get()方法的链式调用,既简洁又能彻底避免KeyError:
answer = results.get(the_feature, {}).get("throughput", "NA")
逻辑说明
- 第一次调用
results.get(the_feature, {}):如果目标特征the_feature不在results的顶层键中,会返回一个空字典{},而非抛出异常。 - 第二次调用
.get("throughput", "NA"):从获取到的子字典(或空字典)中提取throughput值,若该键不存在则返回预设的"NA"。
你也可以用异常捕获的方式实现,适合需要额外处理异常场景的情况:
try: answer = results[the_feature]["throughput"] except KeyError: answer = "NA"
内容的提问来源于stack exchange,提问作者Akshay J
相关产品推荐
相关产品推荐

