为何出现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
相关产品推荐
相关产品推荐

