【发布时间】:2020-08-25 15:09:32
【问题描述】:
以下是我的字典。如何检查给定值是否在字典中。例如,如果用户输入一个数字 129,那么如何检查该数字是否存在于键 A 或 B 中?
studentData = {
'A': [127, 104],
'B': [128, 204, 205, 118]
}
if studID <= 0 :
print ('Invalid id. Student id must be positive')
studID = int(input('Enter student id: '))
elif studID in studentData.values() == True: # how to check if input exist?
print (f'fail')
else:
studentData[modCode].append(int(studID))
print ("complete")
break
【问题讨论】:
-
if number in studentData['A'] or number in studentData['B']? -
if any(studID in vals for vals in studentData.values()) -
studentData.values()给出了一个(整数列表)列表。您需要检查studID是否在(int 列表)的每个 中。您目前只需检查studID是否在列表列表中(显然不是,因为studID是一个不在列表列表中的int) -
@GreenCloakGuy,“你需要这样做,这就是为什么”比“这样做”更有帮助。
-
@GreenCloakGuy 谢谢你是对的 :))
标签: python dictionary