pythonloopsdictionaryappendkey-value

Why is my code not appending into my dictionary a value under a key despite complying with the loop parameters?


I'm sorting grades by number ranges and adding them to my dictionary keys. For some reason my code is ignoring value 68 altogether.

My code:

import numpy as np

exam_results = np.array(
    [
        42,  56,  59,  76,  43,  34,  62,  51,  50,  65,  
        66,  50,  46,  5,  79, 99,  51,  26,  35,   8,  
        34,  47,  64,  58,  61,  12,  30,  63,  20,  68
    ]
)

summarized_data = {'excellent': [],
                   'good': [],
                   'average': [],
                   'passable': [],
                   'failed': []
                  }

count = 0
for er in exam_results:
    count += 1
    if count < len(exam_results):
        if er >= 90:
            summarized_data["excellent"].append(int(er))
        elif 70 <= er <= 89:
            summarized_data["good"].append(int(er))
        elif 50 <= er <= 69:
            summarized_data["average"].append(int(er))
        elif 20 <= er <= 49:
            summarized_data["passable"].append(int(er))
        else:
            summarized_data["failed"].append(int(er))

for result in summarized_data:
    print(result, '-', summarized_data[result])

print(np.sort(exam_results))

Result:

excellent - [99]
good - [76, 79]
average - [56, 59, 62, 51, 50, 65, 66, 50, 51, 64, 58, 61, 63]
passable - [42, 43, 34, 46, 26, 35, 34, 47, 30, 20]
failed - [5, 8, 12]
[ 5  8 12 20 26 30 34 34 35 42 43 46 47 50 50 51 51 56 58 59 61 62 63 64
65 66 68 76 79 99]

Expected result under "average":

average - [56, 59, 62, 51, 50, 65, 66, 50, 51, 64, 58, 61, 63, 68]

Solution

  • This is a simple off by one error.

    The line:

     if count < len(exam_results):
    

    Should be changed to:

     if count <= len(exam_results):
    

    Otherwise, the last element in the array of exam results (score 68) is missed.

    With that change, the output is:

    excellent - [99]
    good - [76, 79]
    average - [56, 59, 62, 51, 50, 65, 66, 50, 51, 64, 58, 61, 63, 68]
    passable - [42, 43, 34, 46, 26, 35, 34, 47, 30, 20]
    failed - [5, 8, 12]
    [ 5  8 12 20 26 30 34 34 35 42 43 46 47 50 50 51 51 56 58 59 61 62 63 64
     65 66 68 76 79 99]
    

    That said, the way the loop is written, with the count increment, is unnecessary. You could simply have written the following for the main loop and the program would still work.

    for er in exam_results:
        if er >= 90:
            summarized_data["excellent"].append(int(er))
        elif 70 <= er <= 89:
            summarized_data["good"].append(int(er))
        elif 50 <= er <= 69:
            summarized_data["average"].append(int(er))
        elif 20 <= er <= 49:
            summarized_data["passable"].append(int(er))
        else:
            summarized_data["failed"].append(int(er))