如何检查字典中是否存在值

时间:2020-08-25 15:09:32

标签: python dictionary

以下是我的字典。如何检查字典中是否有给定值。例如,如果用户输入数字129,那么如何检查数字AB中是否存在该数字?

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 

2 个答案:

答案 0 :(得分:-2)

假设以下内容:

studentData = {
    'A': [127, 130, 123, 210, 109, 128, 204, 206, 111, 129, 103, 116, 112, 209, 122, 202, 121, 101, 113, 104],
    'B': [128, 206, 101, 111, 127, 119, 113, 207, 117, 204, 106, 123, 103, 105, 205, 118]
}

并且modCode包含'A''B'

if studID <= 0 :
    print ('Invalid id. Student id must be positive')
    studID = int(input('Enter student id: '))
elif studID in studentData[modCode]:   # how to check if input exist?
    print (f'Add to Enrolment operation failed. Student is already enrolled in {modCode}')        
else:
    studentData[modCode].append(studID)
    print ("Add to Enrolment operation has successfully completed")

答案 1 :(得分:-2)

您可以轻松地通过键值内的“ in”语句进行检查

for key in ['A', 'B']:
    print(studID in studentData[key])