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...
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
I wrote this code:
def check(student, subject):
x = students.get(student)
y = x[1]
failed = 'F'
if subject in y:
if failed in y[subject]:
print('Failed')
else:
print('Passed')
check('Peter', "DAT130")
What do your think about it? What could be improved? All feedback is appreciated :)