Start learning free

LESSON 103 OF 338 · DICTIONARIES

Updating Dictionary Values in Go: Assigning to a Key

Lesson Read the full explanation

In Go, you update a value in a map by assigning a new value to an existing key:

scores := map[string]int{}
scores["Alice"] = 95
scores["Bob"] = 87

scores["Alice"] = 99     // update: Alice is now 99
scores["Charlie"] = 72   // add new entry

The bracket operator [] both accesses and creates/updates entries. Assigning to an existing key simply overwrites the old value:

scores["Alice"] = 99  // updates Alice

Assignment
Follow the Coding Tutorial and update Alice's score to 99!


Hint
Use scores["Alice"] = 99.

STEP 1 OF 1
    Ctrl + Enter to check

    GO · DICTIONARIES

    Updating Dictionary Values in Go, explained

    Assignment overwrites or creates

    In Go, one syntax both updates and adds map entries: assign to a key with square brackets. If the key already exists, the old value is overwritten. If it doesn't, a new entry is created.

    scores := map[string]int{}
    scores["Alice"] = 95
    scores["Bob"] = 87
    
    scores["Alice"] = 99   // update: Alice is now 99
    scores["Charlie"] = 72 // add a new entry
    

    The map doesn't tell you which of the two happened, and neither is an error. A misspelled key on the left therefore doesn't fail. It silently adds a new entry next to the one you meant to change. Printing the map or checking its length is the quickest way to notice.

    Updating based on the old value

    The same bracket expression can appear on both sides, so the usual compound operators work:

    scores["Alice"] += 1 // 100
    scores["Zed"]++      // Zed was missing: reads 0, stores 1
    

    The second line works because a missing key reads as the zero value, so the increment starts from 0 and stores a real entry. That is handy for counting things, and it is also a way to create an entry by accident.

    Only if the key exists

    When you want to update an entry only if it is already there, check first with the comma-ok form:

    if _, ok := scores["Alice"]; ok {
        scores["Alice"] = 99
    }
    

    Assignment needs a map that was actually created. If the map is nil because it was only declared with var, the assignment panics with assignment to entry in nil map.

    Updating every entry

    To change all the values, loop over the keys and assign through each one. Changing the value of a key that already exists, while ranging over the map, is allowed:

    for name := range scores {
        scores[name] += 5
    }
    fmt.Println(scores) // map[Alice:100 Bob:92]
    

    Printing a map with fmt.Println sorts the keys, so this output is stable. A range loop itself visits the keys in an unspecified order, which doesn't matter here because every key gets the same treatment.

    Update, add and delete side by side

    Three operations cover everything you do to a map's contents. Assigning adds or updates, delete(scores, "Bob") removes an entry, and a lookup reads one. Because assignment can't tell "add" from "update", the length of the map is the easiest way to see which happened: it grows only when the key was new.

    The exercise

    The editor holds a scores map with Alice at 95 and Bob at 87. The single step is to change Alice's score to 99 by assigning to her key. Don't redeclare the map, and don't use := here. The key exists already, and := declares variables, not map entries.

    The solution in Go

    scores := map[string]int{"Alice": 95, "Bob": 87}
    
    scores["Alice"] = 99
    

    After the assignment the map holds Alice at 99 and Bob at 87. The map still has two entries, since the key already existed and was overwritten rather than added.

    Common mistakes

    • Writing scores["Alice"] := 99. The short declaration needs a variable name on its left, so this doesn't compile. Use =.
    • Updating a copy. score := scores["Alice"] followed by score = 99 changes only the local variable. The map is unchanged until you assign to scores["Alice"].
    • Changing a field of a struct stored in a map. With a map[string]Player, the statement m["a"].Score = 5 is a compile error, because map values can't be modified in place. Read the struct, change the copy and store it back.
    • Expecting an order. Updating a value never changes which entries exist, but iteration order over a map is unspecified anyway.

    Key takeaways

    • m[key] = value overwrites an existing entry or creates a new one.
    • += and ++ work on map entries, and a missing key starts at the zero value.
    • A typo in the key adds an entry instead of updating one.
    • Assigning into a nil map panics, so create the map first.
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free