'Check if a student has passed a class

I have a list/dictionary within a dictionary, and I want to check if a specific person has passed the subject or not. The dictionary looks like this:

students = {
'Peter': ['Economy', {'PRO100': 'B', 'PRO110': 'C', 'DAT130': F}], 
'James': ['Psychology', {'MAT120': C, 'PRO100': B, 'DAT120': A}]
}

A is the best grade, and F is failed. 'Economy' and 'Psychology' shows which department the subjects belongs to.

I want a function like this:

def check(student, subject)

where I can check passed/failed as this:

check('Peter', 'PRO100')
>>> True
check('Peter', 'DAT130')
>>> False

I think I can use a for-loop within the function, but I don't know how...



Solution 1:[1]

Try this code:

students = {
'Peter': ['Economy', {'PRO100': 'B', 'PRO110': 'C', 'DAT130': 'F'}], 
'James': ['Psychology', {'MAT120': 'C', 'PRO100': 'B', 'DAT120': 'A'}]
}

passed_grades = ['A', 'B', 'C']

def check(student, subject):
    if students[student][1][subject] in passed_grades:
        return True
    return False

Solution 2:[2]

Here is the answer to your code :

students = {
    'Peter': [
        'Economy', {
            'PRO100': 'B', 
            'PRO110': 'C', 
            'DAT130': 'F'
        }
    ], 
    'James': [
        'Psychology', {
            'MAT120': 'C', 
            'PRO100': 'B', 
            'DAT120': 'A'
        }
    ]
}

good_grades = ['A', 'B', 'C']
bad_grades = ['D', 'E', 'F']

def check(student, subject):
    for subjects in students[student]:
        subjectList = subjects
    
    for grade in subjectList:
        if grade == subject:
            if subjectList[grade] in good_grades:
                return True
            if subjectList[grade] in bad_grades:
                return False
            
    return 'Not Found'
    
    
check('Peter', 'PRO100')

Examples :

check('Peter', 'DAT130')
False
check('James', 'DAT120')
True

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohsen Karimi
Solution 2