Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Python: Update a Dictionary Value by Key

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To update a dictionary value by key in Python, assign the new value to the existing key: my_dict[key] = new_value. If the key exists, its value is replaced; if it does not, the key is added. That one line is the whole answer for the common case. The rest of this guide covers the variations that trip people up: nested dictionaries, conditional updates, bulk updates, and the difference between dict.update() and plain assignment.

What You'll Need

  • Python 3 installed (any recent version; the syntax here works on Python 3.5 and later).
  • A text editor or IDE to write and run a short script.
  • Basic familiarity with creating a dictionary and printing it, so you can confirm the change.

Step-by-Step

  1. Create or load your dictionary. Start with a small example so you can see the effect of each change:
    user = {"name": "Alex", "age": 30, "city": "Berlin"}
  2. Update a single value by key with square-bracket assignment. Put the key in brackets on the left of the equals sign and the new value on the right:
    user["age"] = 31
    print(user)  # {'name': 'Alex', 'age': 31, 'city': 'Berlin'}
    This works whether the key already exists or not. If it does not exist, the key is created.
  3. Use dict.update() when you have several keys to change at once. Pass a dictionary of the changes:
    user.update({"age": 32, "city": "Munich"})
    print(user)  # {'name': 'Alex', 'age': 32, 'city': 'Munich'}
    update() also accepts keyword arguments, so user.update(age=33) works, but only for keys that are valid Python identifiers (no spaces, no leading digits).
  4. Update a nested value by chaining keys. If your dictionary contains another dictionary, index into each level: account["user"]["plan"] = "pro" Each bracket reaches one level deeper. If an intermediate key is missing, you get a KeyError ; see Troubleshooting.
  5. Update only if the key already exists. Use a membership test first so you do not accidentally create new keys:
    if "age" in user:
        user["age"] = 40
    This is the safe pattern when the dictionary is shared or comes from an external source.
  6. Update with a default for missing keys. setdefault() sets a value only when the key is absent, and returns the existing value otherwise:
    user.setdefault("country", "Germany")
    print(user["country"])  # Germany
    Note the difference: setdefault() will not overwrite an existing value. If you want to overwrite, use plain assignment.
  7. Update values based on the old value. Read the current value, compute the new one, then assign it back:
    scores = {"math": 80}
    scores["math"] = scores["math"] + 5
    print(scores)  # {'math': 85}
    For counters, scores["math"] += 5 is the shorter form and does the same thing.
  8. Update every value in the dictionary. Loop over the keys and assign, or build a new dictionary with a comprehension:
    prices = {"apple": 1.0, "pear": 2.0}
    for k in prices:
        prices[k] = prices[k] * 1.1
    print(prices)  # {'apple': 1.1, 'pear': 2.2}
    Do not add or remove keys while looping over the same dictionary; collect changes first, then apply them.
  9. Verify the result. Print the dictionary or the specific key after each change. This catches typos in key names, which are the most common cause of a value appearing not to update.

Common Mistakes

  • Using a string that does not match the key exactly. Keys are case-sensitive and whitespace-sensitive: "Age" and "age" are different keys. If your update seems to do nothing, print list(my_dict.keys()) and compare.
  • Confusing update() with replacing the whole dictionary. my_dict.update(other) merges keys from other into my_dict; it does not replace the dictionary object.
  • Forgetting that setdefault() does not overwrite. People expect it to behave like assignment and are surprised when the old value stays.
  • Trying to index into a missing nested key. account["user"]["plan"] raises KeyError if "user" is absent, because Python evaluates the first bracket before the second.
  • Mutating a dictionary while iterating over it. Adding or deleting keys during a for loop over the same dictionary raises RuntimeError: dictionary changed size during iteration.

Tips

  • Use collections.defaultdict when you are building up values for keys that may not exist yet; it creates a default automatically and avoids KeyError checks.
  • For nested structures that may be incomplete, collections.ChainMap or a small helper function that checks each level is easier to read than long bracket chains.
  • Keep key names consistent in style (all lowercase, underscores) so updates do not silently create near-duplicate keys.
  • If you need a new dictionary rather than changing the original, build one with a comprehension or copy it first with my_dict.copy(); note that copy() is shallow, so nested dictionaries are still shared.

Troubleshooting

The value did not change. Check that you assigned to the same dictionary object you later printed. Rebinding a name (d = new_dict) does not update the original. Print id(my_dict) before and after if you suspect this.

You get a KeyError. The key you are indexing does not exist. Print the keys, or use my_dict.get(key, default) to read without raising. For nested access, check each level with in before indexing.

You get TypeError: 'str' object does not support item assignment. You are indexing a string, not a dictionary. This usually means an earlier lookup returned a string where you expected a nested dictionary; print the intermediate value to confirm.

update() seems to ignore some keys. It does not ignore them; it overwrites existing keys and adds new ones. If a key appears unchanged, the value you passed may be equal to the existing one, or the key name differs by case or whitespace.

The dictionary changes size during a loop. Collect the keys to change in a list first, then loop over that list and assign. Deleting keys during iteration has the same problem; iterate over list(my_dict) instead.

Frequently Asked Questions

How do I update a dictionary value by key without adding a new key?

Test membership first: if key in my_dict: my_dict[key] = value. Without the test, assignment creates the key if it is missing.

What is the difference between my_dict[key] = value and my_dict.update({key: value})?

For a single key they have the same effect. update() is convenient for several keys at once and accepts another dictionary or keyword arguments.

Can I update a nested dictionary value in one line?

Yes, by chaining brackets: my_dict["outer"]["inner"] = value. Every intermediate key must already exist, or you will get a KeyError.

Does setdefault() overwrite an existing value?

No. It returns the existing value and only sets the default when the key is absent. Use plain assignment to overwrite.

How do I update all values in a dictionary at once?

Loop over the keys and reassign each value, or create a new dictionary with a comprehension. Avoid adding or removing keys during the same loop.

Why does my update create a second key that looks the same?

Dictionary keys are case-sensitive and whitespace-sensitive. "Name", "name" and "name " are three different keys, so check for stray spaces or capitalisation.