You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典值为整数时返回字符串及空字典KeyError问题排查

问题解决:字典为空时触发KeyError的修复方案

问题原因

  1. 直接访问不存在的键触发KeyError:原代码第一个if分支直接通过my_data["distance"]取值,当字典中没有该键时,Python会直接抛出KeyError,根本走不到else分支。
  2. 条件判断逻辑错误:elif 'speed' and 'time' in my_data的写法有问题,'speed'是个非空字符串,永远会被判定为True,所以实际只检查了'time'是否在字典里,不符合需要同时存在speed和time的逻辑。
  3. 拼写与语法小问题:存在两处拼写错误(distination→destination,Disntace→Distance),还有返回字符串多了个多余的to。

修正后的代码

my_dict = {
    # "distance": 500.5,
    # 'speed': 60,
    # 'time': 55
}

def rout_info(my_data):
    # 先检查distance键是否存在,再判断值的类型
    if "distance" in my_data and type(my_data["distance"]) is int:
        return f'Distance to your destination is {my_data["distance"]}'
    # 同时校验speed和time两个键是否存在
    elif 'speed' in my_data and 'time' in my_data:
        return f'Distance to your destination is {my_data["speed"] * my_data["time"]}'
    else:
        return 'No distance info available'

print(rout_info(my_dict))

关键修改说明

  • 规避KeyError:先通过"distance" in my_data判断键是否存在,确认存在后再访问对应的值并判断类型,确保不会因为键不存在报错。
  • 修正条件逻辑:把'speed' and 'time' in my_data改成'speed' in my_data and 'time' in my_data,保证只有两个键都存在时才进入该分支。
  • 修复小问题:修正拼写错误,去掉返回字符串里多余的to,让语句更通顺。

内容的提问来源于stack exchange,提问作者egrqX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 07:09:57