-4

The following is my dictionary. How can I check if a given value is in the dictionary. For example, if user enter a number 129, then, how do I check if the number exist in either key A or 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 
Kang Chen
  • 3
  • 2
  • 2
    `if number in studentData['A'] or number in studentData['B']`? – mkrieger1 Aug 25 '20 at 15:12
  • 1
    `if any(studID in vals for vals in studentData.values())` – Green Cloak Guy Aug 25 '20 at 15:12
  • 1
    `studentData.values()` gives a list of (lists of ints). You need to check if `studID` is in _each_ of the (list of int). You currently just check if `studID` is in the list of lists (which it obviously isn't, because `studID` is an `int` which isn't in the list of lists) – Pranav Hosangadi Aug 25 '20 at 15:15
  • @GreenCloakGuy, "You need to do this and here's why" helps more than "Do this". – Pranav Hosangadi Aug 25 '20 at 15:17
  • @GreenCloakGuy thanks you are right :)) – Kang Chen Aug 25 '20 at 15:23
  • https://stackoverflow.com/questions/8214932/how-to-check-if-a-value-exists-in-a-dictionary-python – George Aug 25 '20 at 22:00
  • Does this answer your question? [How to check if a value exists in a dictionary (python)](https://stackoverflow.com/questions/8214932/how-to-check-if-a-value-exists-in-a-dictionary-python) – George Aug 25 '20 at 22:01

2 Answers2

-2

Assuming the following:

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]
}

And that modCode contains either 'A' or '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")
Ajordat
  • 1,320
  • 2
  • 7
  • 19
-2

you can easily check with the "in" statement within the value of the key

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