Start learning free

LESSON 205 OF 285 · PROJECTS: EVERYDAY PROGRAMS

Report Card V5 in Go: Map of Grades Sorted by Subject

Practice Read the full explanation

Use a dictionary, a loop, and conditionals to print each subject with its letter grade in alphabetical order.

You start with:

grades := map[string]int{"Math": 92, "English": 78, "Science": 85, "History": 67}

Build:

English: C
History: D
Math: A
Science: B

Rules:

  • Visit the subjects in alphabetical order.
  • Look up each subject's score in the dictionary and apply the grading scale (90+ A, 80s B, 70s C, 60s D, else F).
  • On each iteration print the subject, a colon and a space, then the grade, for example English: C.

Use a map[string]int - collect keys into a []string slice, sort with sort.Strings, then iterate.

grades := map[string]int{"Math": 92, "English": 78, "Science": 85, "History": 67}

subjects := make([]string, 0, len(grades))
for subject := range grades {
    subjects = append(subjects, subject)
}
sort.Strings(subjects)
for _, subject := range subjects {
    score := grades[subject]
    var grade string
    if score >= 90 {
        grade = "A"
    } else if score >= 80 {
        grade = "B"
    } else if score >= 70 {
        grade = "C"
    } else if score >= 60 {
        grade = "D"
    } else {
        grade = "F"
    }
    fmt.Println(subject + ": " + grade)
}

STEP 1 OF 12
    Ctrl + Enter to check

    GO · PROJECTS: EVERYDAY PROGRAMS

    Report Card V5 in Go, explained

    Problem overview

    Version 5 stores the report card as a map from subject name to score:

    grades := map[string]int{"Math": 92, "English": 78, "Science": 85, "History": 67}
    

    The program prints each subject with its letter grade, in alphabetical order of the subjects. The scale is unchanged: 90 and above is A, 80s are B, 70s are C, 60s are D and the rest F. The expected output is:

    English: C
    History: D
    Math: A
    Science: B
    

    Approach: a map has no order, so sort the keys

    A Go map doesn't remember the order of its entries, and a for ... range over a map visits them in an order that can change from one run to the next. Printing straight from the map would give the right lines in an unpredictable order. The same program printed the subjects as [History Math English Science] in one run and as [English Science History Math] in another.

    The fix has two parts. First collect the keys into a slice, which does have an order. Then sort the slice and walk it, looking up each score in the map by its key. The map holds the data, and the sorted slice decides the order.

    Here is what the key slice looks like before and after sort.Strings, for a run in which the loop happened to collect the keys in this order:

    before: [History Math English Science]
    after:  [English History Math Science]
    

    Only the slice changes. The map itself is untouched, and each lookup grades[subject] still finds the right score, because the key is what identifies it. The separation is the idea of the lesson: the map is good at lookup by name, the slice is good at holding an order, and you need both to print in a fixed order.

    Step by step

    1. Create the slice. subjects := make([]string, 0, len(grades)) makes an empty slice of strings with room reserved for one name per subject. The length is 0 and the capacity is len(grades).
    2. Collect the keys. for subject := range grades gives the keys of the map, one per pass. The line that appends each key to subjects goes inside this loop.
    3. Sort. sort.Strings(subjects) sorts the slice in place, alphabetically.
    4. Walk the sorted slice. for _, subject := range subjects gives index and value for each element. The blank identifier _ discards the index, which the loop doesn't need.
    5. Look up the score. score := grades[subject] reads the value stored under that key.
    6. Declare grade. var grade string starts as an empty string.
    7. Run the ladder. Test 90, 80, 70 and 60 from the top with if and else if, and finish with an else for "F".
    8. Print. After the ladder, inside the loop, print the subject, ": " and the grade.

    The solution in Go

    grades := map[string]int{"Math": 92, "English": 78, "Science": 85, "History": 67}
    
    subjects := make([]string, 0, len(grades))
    for subject := range grades {
        subjects = append(subjects, subject)
    }
    sort.Strings(subjects)
    for _, subject := range subjects {
        score := grades[subject]
        var grade string
        if score >= 90 {
            grade = "A"
        } else if score >= 80 {
            grade = "B"
        } else if score >= 70 {
            grade = "C"
        } else if score >= 60 {
            grade = "D"
        } else {
            grade = "F"
        }
        fmt.Println(subject + ": " + grade)
    }
    

    The code uses the fmt and sort packages. The details worth knowing:

    • Range over a map yields keys first. With one loop variable you get the key. With two, for key, value := range m, you get both. The loop that collects keys needs only the keys.
    • Range over a slice yields the index first. That is why the second loop writes _, subject. Writing for subject := range subjects would give the index, a number, and the lookup grades[subject] wouldn't compile.
    • make with a capacity. make([]string, 0, n) avoids repeated reallocation while appending. subjects := []string{} would work too, only less efficiently.
    • sort.Strings compares byte by byte. Uppercase letters come before lowercase ones. For the keys art, Biology, chemistry and Dance the sorted order is Biology, Dance, art, chemistry. This lesson's subjects all start with a capital letter, so plain alphabetical order results.
    • A missing key gives the zero value. grades["Art"] returns 0 and doesn't report an error. The two-value form score, ok := grades["Art"] tells you whether the key exists. Here every looked-up key comes from the map itself, so the plain form is safe.

    Complexity

    With n subjects, collecting the keys is O(n), sorting is O(n log n) and the grading loop is O(n), since each map lookup takes constant time on average. The total is O(n log n). The extra space is the subjects slice, O(n).

    Edge cases and common mistakes

    • Skipping the sort. The output may happen to look right on one run and be in another order the next time. The lesson's tests need the alphabetical order every time.
    • Sorting the map. A map can't be sorted. Only the slice of keys can.
    • Mixed case. Subjects such as art and Dance sort with all capitals first. With the data in this lesson that doesn't arise.
    • An empty map. The key slice stays empty, the loops don't run and nothing is printed.
    • Boundary scores. A subject scoring exactly 60 gets D, and 59 gets F. With the map art: 95, Biology: 59, chemistry: 60, Dance: 100 the output is Biology: F, Dance: A, art: A and chemistry: D.

    Testing

    • The starting map prints the four lines English: C, History: D, Math: A and Science: B, in that order, on every run.
    • An empty map prints nothing.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free