To update an item in a Python dictionary, assign a new value to an existing key using square brackets: my_dict[key] = new_value. If the key already exists, its value is replaced; if it doesn't, a new key-value pair is added. That's the whole answer for the common case. The rest of this guide covers the variations you'll actually hit: updating multiple keys at once, merging dictionaries, changing values based on the old value, and the mistakes that cause silent bugs.

What You'll Need

  • A working Python 3 installation (any recent version; the syntax here is stable across Python 3.x).
  • A text editor or IDE to write and run your script, or an interactive Python shell for quick tests.
  • Basic familiarity with creating a dictionary and reading values from it.

Step-by-Step

  1. Create or load your dictionary. Start with a dictionary that has the keys you want to change. For example: inventory = {'apples': 10, 'bananas': 5, 'oranges': 8}. In real code this might come from a JSON file, an API response, or user input.
  2. Confirm the key exists before updating (optional but recommended). Use if 'apples' in inventory: to check. This avoids accidentally creating a new key when you meant to update an existing one. You can also use inventory.get('apples') to read the current value safely.
  3. Assign the new value using square brackets. Write inventory['apples'] = 12. This is the primary update operation. The key 'apples' now maps to 12. If 'apples' had not existed, this line would have added it.
  4. Verify the change. Print the dictionary or the specific key: print(inventory['apples']) should output 12. You can also print the whole dictionary to see that other keys are untouched.
  5. Update multiple keys in one go (if needed). Use the update() method with another dictionary: inventory.update({'bananas': 7, 'oranges': 9}). This changes both values. If a key in the argument doesn't exist, it is added. You can also pass keyword arguments: inventory.update(bananas=7), but only for keys that are valid Python identifiers (no spaces, not starting with a digit).
  6. Update a value based on its current value. For counters or accumulators, read the old value and assign the new one: inventory['apples'] = inventory['apples'] + 1 or the shorthand inventory['apples'] += 1. For keys that might not exist yet, use inventory['apples'] = inventory.get('apples', 0) + 1 to avoid a KeyError.
  7. Merge another dictionary into yours. The update() method also works with any mapping or iterable of key-value pairs. For example, inventory.update({'pears': 4}) adds a new key. In Python 3.9 and later, you can also use the merge operator: inventory |= {'pears': 4}. This modifies the original dictionary in place.
  8. Handle nested dictionaries carefully. If your dictionary contains other dictionaries, updating a nested value requires drilling down: inventory['apples'] = {'count': 12, 'price': 0.5} replaces the whole nested dictionary. To change only one field inside it, do inventory['apples']['count'] = 12. Make sure the nested dictionary already exists; otherwise you'll get a KeyError.
  9. Consider using a defaultdict for automatic defaults. If you frequently update keys that may not exist, collections.defaultdict can simplify your code: from collections import defaultdict; inventory = defaultdict(int). Then inventory['apples'] += 1 works even if 'apples' was never set, because the default value (0) is used automatically.
  10. Save or return the updated dictionary. If you loaded the dictionary from a file or database, write it back using the appropriate method (e.g., json.dump for JSON). Otherwise, return it from your function or continue using it in your program.

Common Mistakes

  • Using assignment when you meant to check existence. Writing inventory['apples'] = 12 when 'apples' doesn't exist will add a new key, not raise an error. If you need to update only existing keys, check with in first.
  • Forgetting that dictionaries are mutable and shared. If you pass a dictionary to a function and update it inside, the original dictionary is changed. To avoid this, make a copy first: new_dict = original.copy() (shallow copy) or copy.deepcopy(original) for nested structures.
  • Assuming update() returns a new dictionary. It modifies the dictionary in place and returns None. So result = inventory.update({...}) sets result to None, not the updated dictionary.
  • Using a key that doesn't exist without a default. Accessing inventory['apples'] when 'apples' is missing raises a KeyError. Use get() or check with in to avoid crashes.
  • Modifying a dictionary while iterating over it. If you loop over inventory.keys() and add or remove keys inside the loop, Python raises a RuntimeError. Collect the changes first, then apply them after the loop, or iterate over a copy: for key in list(inventory.keys()):.

Tips

  • Use dict.setdefault(key, default) to set a value only if the key is missing. It returns the existing value if present, so you can chain updates.
  • For complex updates, consider using a dataclass or a custom class instead of a nested dictionary; it makes your code more readable and less error-prone.
  • When updating from user input, validate the key and value types to avoid unexpected behavior later.
  • Remember that dictionary keys must be hashable (strings, numbers, tuples). If you try to use a list as a key, you'll get a TypeError.
  • Use pprint (pretty-print) to inspect large dictionaries after updates; it formats nested structures for easier reading.

Troubleshooting

If your update doesn't seem to take effect, check these in order:

  • KeyError: You tried to update a nested value but the parent key doesn't exist. Create the parent dictionary first or use setdefault.
  • TypeError: 'str' object does not support item assignment: You're trying to update a string as if it were a dictionary. Make sure your variable is actually a dict.
  • Value not changing: You might be updating a copy of the dictionary, not the original. Check if you used copy() or if the dictionary is inside a function and not returned.
  • Unexpected new keys: You used assignment on a key that didn't exist. Use in to check before assigning if you only want to modify existing keys.
  • RuntimeError during iteration: You modified the dictionary size while looping. Iterate over a list of keys instead.

Frequently Asked Questions

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

Check if the key exists first: if key in my_dict: my_dict[key] = new_value. This ensures you only modify existing keys.

What's the difference between dict.update() and assignment?

Assignment updates a single key. update() can update multiple keys at once from another dictionary or iterable of key-value pairs, and it adds new keys if they don't exist.

Can I update a dictionary with another dictionary that has overlapping keys?

Yes. update() overwrites the values for overlapping keys with the values from the argument dictionary.

How do I update a nested dictionary value?

Access the nested dictionary first: my_dict['outer']['inner'] = new_value. Ensure the outer key exists and its value is a dictionary.

Is there a way to update a dictionary and get a new one without modifying the original?

Yes. Use the merge operator | (Python 3.9+): new_dict = old_dict | {'key': 'new_value'}. This creates a new dictionary with the update applied, leaving old_dict unchanged.

What happens if I update a dictionary with a key that doesn't exist?

The key-value pair is added to the dictionary. If you want to avoid adding new keys, check for existence first.