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

Python循环遍历嵌套字典判断值存在时报int不可迭代错误如何解决

报错原因

字典中第一个键Bull's eye对应的Range字段是整数类型60,而in运算符要求右侧操作数是可迭代对象,对整数直接用in判断就会触发类型错误。

修正思路

  • 先判断每个Range字段的类型:如果是整数,直接比较数值是否相等;如果是range对象,再用in判断是否在范围内
  • 额外优化:不要用dict作为变量名,会覆盖Python内置的字典类型,避免后续出现隐性问题

修正后代码

# 变量名替换为data,避免覆盖内置类型
data = {
    "Bull's eye": {"Points": 50, "Range": 60},
    "Bull": {"Points": 25, "Range": range(55, 59)},
    "Outer value": {"Points": range(0, 20), "Range": range(1, 54)},
}
number = 2
for key in data:
    current_range = data[key]["Range"]
    # 按类型做对应校验逻辑
    if isinstance(current_range, int):
        is_match = number == current_range
    else:
        is_match = number in current_range
    if is_match:
        print(f"Value is in {key}")

运行后会输出Value is in Outer value,和预期结果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:27:01