Smart Systems for Home

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

Python: How to Update a Value in a Dictionary

· 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 using square brackets: my_dict[key] = new_value. This works because dictionaries are mutable, and assignment to an existing key replaces its value in place. If the key does not exist, the same syntax adds a new key-value pair instead of updating. For conditional updates, use dict.update() with another dictionary or iterable of key-value pairs, or the |= operator in Python 3.9 and later. The sections below cover the exact syntax, common pitfalls, and practical examples so you can update values confidently.

What You'll Need

  • A working Python installation (version 3.6 or later recommended; |= requires 3.9+).
  • A text editor or IDE to write and run your code.
  • Basic familiarity with Python dictionaries and key-value pairs.

Step-by-Step

  1. Create or obtain your dictionary. Start with a dictionary that already contains the key you want to update, for example: inventory = {'apples': 10, 'bananas': 5}. If you are loading from a file or API, assign the result to a variable first.
  2. Check that the key exists (optional but recommended). Use if 'apples' in inventory: before updating if you need to avoid accidentally adding a new key. For a quick check in the REPL, just print the dictionary or use inventory.keys().
  3. Assign the new value using square brackets. Write inventory['apples'] = 12. This replaces the value for the existing key. The dictionary now shows {'apples': 12, 'bananas': 5}. This is the most direct and readable way to update a single value.
  4. Update multiple keys at once with update(). Call inventory.update({'apples': 15, 'bananas': 8}). This updates existing keys and adds any new ones. You can also pass keyword arguments: inventory.update(apples=15, bananas=8). Note that keyword arguments only work for string keys that are valid identifiers.
  5. Use the merge operator |= (Python 3.9+). Write inventory |= {'apples': 20}. This behaves like update() but is shorter. It modifies the dictionary in place. If you are on an older Python version, stick with update().
  6. Update a value based on its current value. For counters or accumulations, read the old value and assign the new one: inventory['apples'] = inventory['apples'] + 1. The shorthand inventory['apples'] += 1 does the same. If the key might not exist, use inventory['apples'] = inventory.get('apples', 0) + 1 to avoid a KeyError.
  7. Update nested dictionaries carefully. If your dictionary contains another dictionary as a value, update the inner key directly: data['user']['age'] = 31. Make sure the outer key exists first, or use data.setdefault('user', {})['age'] = 31 to create the inner dictionary if missing.
  8. Verify the result. Print the dictionary or inspect it in your debugger. Confirm that only the intended keys changed and that no unexpected keys were added.

Common Mistakes

  • Updating a key that does not exist. Using my_dict['missing'] = value adds a new key instead of updating. If you expected an error, check with in first or use my_dict.get('missing') to see if it returns None.
  • Assuming update() returns a new dictionary. dict.update() modifies the dictionary in place and returns None. Writing new_dict = my_dict.update({...}) sets new_dict to None.
  • Using += on a missing key. my_dict['count'] += 1 raises KeyError if 'count' is not already present. Use my_dict['count'] = my_dict.get('count', 0) + 1 instead.
  • Mutating a dictionary while iterating over it. Changing keys during a for key in my_dict: loop can raise RuntimeError: dictionary changed size during iteration. Iterate over a copy: for key in list(my_dict):.
  • Confusing update() with reassignment. my_dict = {'a': 2} replaces the whole dictionary object. If other variables reference the original, they will not see the change. Use my_dict.update(...) or item assignment to modify in place.

Tips

  • Use dict.get(key, default) when reading values that might not exist, especially before arithmetic updates.
  • For bulk updates from a list of pairs, dict.update() accepts an iterable of (key, value) tuples, e.g., my_dict.update([('a', 1), ('b', 2)]).
  • Prefer |= for a clean in-place merge in Python 3.9+, but remember it is not available in older versions.
  • When updating nested structures, consider using collections.defaultdict to avoid missing-key errors.
  • Always test updates on a copy if the dictionary is shared across functions, to avoid unintended side effects.

Troubleshooting

  • KeyError when updating: The key you tried to update does not exist. Check spelling and case sensitivity. Use in or get() to confirm presence.
  • Value not changing: Ensure you are modifying the dictionary in place, not reassigning a new dictionary to a local variable inside a function without returning it. Also check that you are not updating a copy created with dict.copy() or copy.deepcopy().
  • RuntimeError during iteration: As noted, do not add or remove keys while looping. Collect changes and apply after the loop, or iterate over a list of keys.
  • Unexpected new keys: If you use update() with a dictionary that contains extra keys, those keys are added. Filter the update dictionary to only the keys you intend to change.
  • TypeError with |=: The right-hand operand must be a mapping or an iterable of key-value pairs. If you pass a list of single values, it will fail.

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. Alternatively, use my_dict.update({key: new_value}) only after confirming the key is present. There is no built-in method that updates only existing keys and ignores missing ones, so the explicit check is the safest approach.

What is the difference between dict.update() and assigning with square brackets?

Square bracket assignment updates or adds a single key. update() can modify multiple keys at once and also adds new keys. Both modify the dictionary in place. Use update() for bulk changes and square brackets for single, targeted updates.

Can I update a dictionary value using a variable as the key?

Yes. Use the variable inside square brackets: my_dict[my_key] = new_value. The variable must hold a hashable object, typically a string or number. This is common when iterating over keys or reading key names from user input.

How do I update a value in a nested dictionary?

Access the nested dictionary first, then assign: my_dict['outer']['inner'] = new_value. Ensure the outer key exists and its value is a dictionary. If the outer key might be missing, use my_dict.setdefault('outer', {})['inner'] = new_value.

Does updating a dictionary change the original if it was passed to a function?

Yes, because dictionaries are mutable and passed by reference. If you modify the dictionary inside a function using item assignment or update(), the caller sees the changes. To avoid this, pass a copy: func(my_dict.copy()) or use copy.deepcopy() for nested structures.

What happens if I update a key with a different type?

Python dictionaries allow values of any type. Updating a key with a value of a different type simply replaces the old value. The key itself must remain hashable; you cannot change a key in place, but you can delete and re-add it if needed.