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

为何出现TypeError: '>='不支持dict_values与int实例比较?

问题解决:筛选字典中值≥65的键

先明确你代码里的几个问题:

  • for values in scores 遍历字典时,默认拿到的是键,不是值,变量名混淆了逻辑。
  • scores.values() 返回的是字典所有值的集合(dict_values 对象),不能直接和单个整数65比较,你需要的是当前遍历项对应的具体值。
  • scores.keys() 返回的是所有键的集合,不是当前符合条件的单个键,不能直接添加到列表里。

修正后的普通循环代码

scores = {"John": 81, "Doe": 26, "Jane": 80, "Smith": 22, "Bob": 89}
passed = []
# 用items()方法同时遍历字典的键和值
for name, score in scores.items():
    if score >= 65:
        passed.append(name)
print(passed)

更简洁的列表推导式写法

如果想让代码更紧凑,用Python列表推导式可以一行完成需求:

scores = {"John": 81, "Doe": 26, "Jane": 80, "Smith": 22, "Bob": 89}
passed = [name for name, score in scores.items() if score >= 65]
print(passed)

两种写法运行后都会输出:['John', 'Jane', 'Bob'],完全符合你的目标。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:12:02