Start learning free

LESSON 101 OF 344 · DICTIONARIES

Updating Dictionary Values in Python: Assigning to a Key

Lesson Read the full explanation

You can update an existing value in a Python dictionary by assigning a new value to an existing key:

scores = {"Alice": 95, "Bob": 87}

scores["Alice"] = 99    # update existing key
scores["Charlie"] = 72  # add new key

If the key exists, the value is overwritten. If it doesn't exist, a new entry is added.

d = {"x": 1}
d["x"] = 100   # x is now 100
d["y"] = 200   # new key "y" added
print(d)       # {"x": 100, "y": 200}

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

    PYTHON · DICTIONARIES

    Updating Dictionary Values in Python, explained

    Assigning to a key

    Dictionaries can change after you create them. To give an existing key a new value, assign to it with square brackets, the same syntax you use to read it. The new value replaces the old one:

    scores = {"Alice": 95, "Bob": 87}
    
    scores["Alice"] = 99
    print(scores)  # {'Alice': 99, 'Bob': 87}
    

    Only the pair for "Alice" changed. The other pairs stay where they are, and so does the order of the keys.

    Updating versus adding

    The same statement does two jobs, depending on whether the key is already there. If the key exists, its value is overwritten. If it does not exist, a new pair is added at the end:

    d = {"x": 1}
    d["x"] = 100   # x already exists, so its value is replaced
    d["y"] = 200   # y is new, so a pair is added
    print(d)       # {'x': 100, 'y': 200}
    

    Python does not warn you either way. That is convenient, but it also means that a typo in a key quietly creates a new pair instead of updating the one you meant:

    s = {"Alice": 95}
    s["alice"] = 1
    print(s)  # {'Alice': 95, 'alice': 1}
    

    Keys are case sensitive, so "alice" is a different key from "Alice", and the dictionary now has two entries. If you only want to update keys that already exist, check first with if key in d:.

    Computing the new value from the old one

    The new value can depend on the old one. Read it, change it and assign it back. The shortcut operators work on dictionary entries as they do on variables:

    scores = {"Alice": 99, "Bob": 87}
    scores["Alice"] += 1
    scores["Bob"] = scores["Bob"] + 3
    print(scores)  # {'Alice': 100, 'Bob': 90}
    

    This works only for keys that exist. Using += on a missing key first needs to read it, so it raises KeyError. When the key may be missing, write d[key] = d.get(key, 0) + 1 to start from zero.

    Changing several entries at once

    The update() method takes another dictionary and applies all its pairs, replacing existing keys and adding new ones:

    scores = {"Alice": 100, "Bob": 87}
    scores.update({"Bob": 90, "Dan": 60})
    print(scores)  # {'Alice': 100, 'Bob': 90, 'Dan': 60}
    

    Updating every entry

    To change all the values, loop over the keys and assign to each. Changing the value of a key that already exists is safe while looping. What you must not do is add or remove keys during the loop, because that changes the dictionary's size while Python is walking through it.

    scores = {"Alice": 99, "Bob": 87}
    for name in scores:
        scores[name] += 5
    print(scores)  # {'Alice': 104, 'Bob': 92}
    

    Nothing forces the new value to have the same type as the old one. After d["x"] = "now text", a key that held a number holds a string. That flexibility is useful, but it is also an easy way to break code that expects numbers.

    Dictionaries change in place

    Unlike strings, a dictionary is mutable: assigning to a key modifies the dictionary itself and creates no new one. This matters when two names refer to the same dictionary:

    a = {"x": 1}
    b = a
    b["x"] = 2
    print(a)  # {'x': 2}
    
    c = a.copy()
    c["x"] = 3
    print(a, c)  # {'x': 2} {'x': 3}
    

    The line b = a does not copy anything. Both names point to one dictionary, so a change through b shows up in a. Use copy() when you want an independent dictionary.

    Common mistakes

    • Using == instead of =. The line scores["Alice"] == 99 compares and does not update. It produces True or False and changes nothing.
    • Expecting an error for a missing key. An assignment never raises KeyError. It silently adds the pair.
    • Typos in keys. A wrong spelling or case creates a new entry. Compare len(d) before and after if you are unsure.
    • Replacing the whole dictionary by accident. Writing scores = {"Alice": 99} throws away the other pairs. Assign to the key instead.
    • Forgetting the quotes. scores[Alice] = 99 looks for a variable named Alice.

    The exercise, step by step

    The lesson starts with scores already containing Alice at 95 and Bob at 87, and asks you to raise Alice's score to 99.

    1. Name the entry. Write scores["Alice"], with the key as a string in square brackets.
    2. Assign the new value. Put = 99 after it. Because "Alice" already exists, the old value 95 is replaced.
    scores = {"Alice": 95, "Bob": 87}
    
    scores["Alice"] = 99
    

    No new variable is needed this time, because you are changing the dictionary itself. After this line, scores is {'Alice': 99, 'Bob': 87}, and the dictionary still has two entries.

    Key takeaways

    • d[key] = value overwrites the value if the key exists and adds a new pair if it does not.
    • No error is raised for a new key, so typos create extra entries.
    • d[key] += 1 needs an existing key. Use get() with a default otherwise.
    • Dictionaries are changed in place, and assigning one name to another shares the same dictionary.
    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free