Smart Systems for Home

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

How to Update a Value in a Dictionary (Python)

· 6 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 value in a Python dictionary, assign a new value to an existing key with the syntax my_dict[key] = new_value. If the key already exists, its value is replaced; if it does not exist, Python adds the key-value pair. That single line is the standard, fastest way to change one entry. For several entries at once, use the update() method. For nested dictionaries, address the inner key directly, such as my_dict['outer']['inner'] = value. This guide covers those methods, the mistakes that cause silent bugs, and how to confirm the change actually happened.

What You'll Need

  • Python 3 installed and working (check with python --version or python3 --version in a terminal).
  • A text editor or IDE to write and run a short script, or an interactive Python session (REPL).
  • A dictionary to work with, either one you define yourself or one returned by a function or loaded from JSON.
  • Basic familiarity with Python syntax: variables, strings as keys, and printing output.

Step-by-Step

  1. Create or obtain your dictionary. In a script or the REPL, define a small test dictionary so you can see changes clearly. For example: user = {'name': 'Sam', 'age': 30, 'city': 'Leeds'}. If your dictionary comes from elsewhere (a JSON file, an API response, a function return), assign it to a variable first so you can inspect and modify it.
  2. Confirm the key exists before changing it. Print the current value with print(user['age']) or check membership with 'age' in user. This tells you whether your next assignment will replace an existing value or create a new key. The distinction matters: a typo in the key creates a duplicate entry rather than updating the one you meant.
  3. Assign the new value using square brackets. Write user['age'] = 31. Python looks up the key 'age', finds it, and replaces the old value. The dictionary's length does not change. Print the dictionary to verify: print(user) should show the updated age alongside the unchanged name and city.
  4. Update several keys at once with update(). Pass a dictionary of changes: user.update({'age': 32, 'city': 'Manchester'}). Existing keys are overwritten and new keys are added in the same call. You can also pass keyword arguments for string keys, such as user.update(age=33), though this only works when the keys are valid Python identifiers.
  5. Handle a missing key safely when you are not sure it exists. If you want to update only when a key is present, guard it: if 'age' in user: user['age'] = 34. If you want to set a value only when the key is absent, use user.setdefault('country', 'UK'), which leaves an existing value untouched. If you want a default when reading, use user.get('age', 0) rather than square brackets, which raise KeyError on a missing key.
  6. Update a value inside a nested dictionary. Address each level in turn: user['address']['postcode'] = 'M1 1AA'. This works only if 'address' already maps to a dictionary. If the outer key might be missing, create it first with user.setdefault('address', {}) and then assign the inner key.
  7. Update values in a loop when the change depends on the old value. To increment every numeric value, for example: for k in scores: scores[k] += 1. Do not add or remove keys while iterating over the same dictionary; iterate over a copy such as list(scores.keys()) if you need to change the structure.
  8. Verify the result. Print the dictionary, or print the specific key, and compare against what you expected. If you are working with a dictionary loaded from a file, remember that changing it in memory does not change the file; you must write it back (for example with json.dump) to persist the update.

Common Mistakes

Typo keys create new entries. Writing user['Age'] = 31 when the key is 'age' adds a second, separate key because Python keys are case-sensitive. The dictionary now holds both values, and later code reading 'age' sees the old one. Print the keys with print(user.keys()) when a change seems to have no effect.

Assuming assignment mutates a copy. Dictionaries are mutable, but if you copy one with copy = original, both names point to the same object, so updating through one name changes the other. Use original.copy() or copy.deepcopy(original) for nested structures when you want an independent version.

Using update() with the wrong argument shape. update() expects a mapping or an iterable of key-value pairs. Passing a plain string or a list of single values raises an error or produces unexpected keys. Pass a dictionary or pairs such as [('age', 31), ('city', 'Leeds')].

Modifying a dictionary while looping over it. Adding or deleting keys during iteration can raise RuntimeError: dictionary changed size during iteration. Iterate over a list of keys instead.

Forgetting that JSON keys are always strings. A dictionary loaded from JSON has string keys, so data[1] will not find a key stored as '1'. Convert the key type before updating.

Tips

Use dict.update() when you have a batch of changes and square-bracket assignment for one-off edits; both are clear and idiomatic. Reach for setdefault() when building nested structures incrementally, since it creates the intermediate dictionary only when needed. When debugging, print id(my_dict) before and after a function call to confirm you are editing the same object rather than a copy. If your dictionary is large and you update it in a hot loop, square-bracket assignment is the direct route; avoid rebuilding the whole dictionary for a single change. Keep a short test snippet that prints the before and after state, so a wrong key shows up immediately instead of surfacing much later in your program.

Troubleshooting

The value did not change. Check for a typo or case mismatch in the key by printing list(my_dict.keys()). Confirm you are updating the same object the rest of your code reads, not a copy made earlier. If the dictionary came from a file or database, confirm you saved it back.

You get KeyError. The key is not present. Use in to test, get() to read with a fallback, or setdefault() to create the key before assigning.

You get TypeError: 'str' object does not support item assignment. You are indexing into a string rather than a dictionary, often because a nested lookup returned a string where you expected a dictionary. Print the type of the intermediate value with type(my_dict['outer']) to find where the structure differs from your assumption.

You get a RuntimeError about dictionary size changing. You are adding or removing keys during iteration. Loop over list(my_dict.keys()) or build a separate list of changes and apply them after the loop.

The nested update fails with KeyError. The outer key does not exist yet. Create it with my_dict.setdefault('outer', {}) and then assign the inner key. If the outer value exists but is not a dictionary, decide whether to replace it or restructure your data.

Frequently Asked Questions

Does assigning to an existing key change the dictionary's size?

No. Replacing the value of an existing key keeps the same number of entries. Only assigning to a key that is not present adds a new entry.

What is the difference between update() and square-bracket assignment?

Both change values. Square brackets set one key at a time; update() applies a whole mapping of changes in one call and also adds any keys that are missing.

How do I update a value only if the key already exists?

Test first with if key in my_dict: and then assign. Alternatively, use setdefault() if you want the opposite behaviour: set a value only when the key is absent.

Why does my update create a duplicate key?

Python keys are case-sensitive and type-sensitive. 'Age', 'age', and 1 are three different keys. Print the keys to spot the mismatch.

Can I update a value inside a list stored in a dictionary?

Yes. Retrieve the list with my_dict['items'] and modify it in place, for example my_dict['items'][0] = 'new'. The dictionary still holds the same list object.

Does updating a dictionary loaded from JSON save the file?

No. Changes stay in memory. Write the dictionary back to the file with the appropriate serialisation function, such as json.dump, to persist them.