如果通过int值循环字典


courses = {"mon":20,
"tues":25,
"wed":13,
"thurs":5,
"fri":25}
for value in courses:
if value == 25:
print("course is full")
elif value >= 20 and key<=24:
print("course is almost full")
elif value<20:
print("plenty of seats left") #here

我得到类型错误'>='在"str"one_answers"int"的实例之间不支持如何修复我的代码?

请注意,当您遍历字典时,您会遍历字典的键。不是价值观。

courses = {
"mon":20,
"tues":25,
"wed":13,
"thurs":5,
"fri":25
}
for day, value in courses.items():
if value == 25:
print(f"{day} course is full")
elif value >= 20 and value<=24:
print(f"{day} course is almost full")
elif value<20:
print(f"{day} course has plenty of seats left")

这很可能是你想要的。

为了只获得值,通过courses.values()而不是courses.items()进行迭代

在字典中循环得到的是键,而不是值。您可以执行以下操作。

courses = {"mon":20,
"tues":25,
"wed":13,
"thurs":5,
"fri":25}
for key in courses:
if courses[key] == 25:
print("course is full")
elif courses[key] >= 20 and courses[key] <= 24:
print("course is almost full")
elif courses[key]<20:
print("plenty of seats left") here

或者,您可以使用for value in courses.values():直接循环这些值。

值是str(键(,不能与比较运算符和int一起使用不需要评估介于两者之间的两个条件,elif肯定只有在满足条件时才会触发一次。。

for value in courses.values():
if value >= 25: print("course is full")
elif value >= 20: print("course is almost full")
elif value < 20: print("plenty of seats left")

最新更新