Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace value at i in Dictionary

I am trying to loop through a dictionary and if it meets a requirement, the requirements being distinction >=70, merit>=60, pass>=50, and fail less than 50 then the value that is currently being passed through the loop will be replaced by the correct classification.

For example, the first value being passed through is mark_1 which is 20 so at 20 in the dictionary I am looking to replace the 20 with "fail"

module_1="Maths"
module_2="English"
module_3="Science"
module_4="Business"
module_5="PE"

mark_1 =20
mark_2=30
mark_3 =40
mark_4=50
mark_5=60

module_marks = {module_1:int(mark_1), 
module_2: int(mark_2),
module_3: int(mark_3),
module_4: int(mark_4),
module_5:int(mark_5)}

marks= classifygrade.classify_grade(module_marks)

And in my other class it defines the method to try and accomplish this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def classify_grade(module_marks):
    for i in module_marks.values():
        if i>=70:
            module_marks[i].update("distinction")
        elif i>=60:
            module_marks[i].update("merit")
        elif i>=50:
            module_marks[i].update("pass")
        else:     
            module_marks[i].update("fail")

>Solution :

The problem is that you’re trying to access a field in a dictionary by its value. You are also trying to return a new dictionary, but you are changing the original dictionary. You should create a separate dictionary and use dict.items() instead. Like this:

def classifyMarks(marks):
    result = {}
    for (subject, grade) in marks.items():
        if grade >= 70:
            result[subject] = "Distinction"
        elif grade >= 60:
            result[subject] = "Merit"
        elif grade >= 50:
            result[subject] = "Pass"
        else:
            result[subject] = "Fail"
    return result


marks = {
    "Maths": 20,
    "English": 30,
    "Science": 40,
    "Business": 50,
    "PE": 60
}

marks = classifyMarks(marks)
print(marks)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading