To update a value in a Python dictionary, assign a new value to the key: my_dict[key] = new_value. If the key exists, its value is replaced; if it does not, the key is added. For updating multiple keys at once, use the update() method with another dictionary or an iterable of key-value pairs. That is the direct answer. The rest of this guide walks through the exact steps, the common traps, and how to handle nested dictionaries and missing keys safely.
What You'll Need
- A working Python installation (version 3.x is assumed; the syntax shown works in all current Python 3 releases).
- A text editor or IDE to write and run your code.
- Basic familiarity with Python dictionaries: curly braces, keys, and values.
- A dictionary to work with, either defined in your script or loaded from a file or API.
Step-by-Step
- Create or identify your dictionary. For example:
user = {'name': 'Alex', 'age': 30, 'city': 'Berlin'}. Know which key you want to change and what the new value should be. - Update a single value by direct assignment. Use square brackets with the key on the left and the new value on the right:
user['age'] = 31. This overwrites the old value. If the key did not exist, Python adds it to the dictionary. This is the fastest and most common method. - Update several keys at once with
update(). Pass a dictionary of the changes:user.update({'age': 32, 'city': 'Munich'}). Existing keys are overwritten; new keys are added. You can also pass keyword arguments:user.update(age=33, country='Germany'). Note that keyword arguments only work when keys are valid Python identifiers (strings without spaces or special characters). - Update a value based on its current value. Read the old value first, then assign the result:
user['age'] = user['age'] + 1or the shorthanduser['age'] += 1. This is common for counters and running totals. - Update a nested dictionary value. Access each level in turn:
user['address']['city'] = 'Hamburg'. This works only if the intermediate keys already exist. Ifaddressmight be missing, check first withif 'address' in user:or useuser.setdefault('address', {})['city'] = 'Hamburg', which creates the inner dictionary if needed. - Update only if the key exists. Use a conditional:
if 'age' in user: user['age'] = 34. This prevents accidentally adding new keys when you only want to modify existing ones. - Update with a default for missing keys. The
setdefault()method returns the existing value if the key is present, or inserts a default and returns it:user.setdefault('country', 'Germany'). It will not overwrite an existing value, so use it when you want to fill gaps rather than replace data. - Verify the result. Print the dictionary or inspect specific keys:
print(user)orprint(user['age']). Confirm that only the intended keys changed and that no unexpected keys were added.
Common Mistakes
- Using
update()with a list of values instead of key-value pairs.update()expects a mapping or an iterable of two-item pairs. Passing a plain list of values raises an error or produces unexpected results. - Assuming
update()replaces the whole dictionary. It merges: keys not mentioned are left untouched. If you need a clean replacement, assign a new dictionary instead. - Forgetting that assignment adds missing keys.
d['typo'] = 1silently creates a new entry. If you meant to modify an existing key, check membership first. - Updating a nested key whose parent does not exist.
d['a']['b'] = 1raisesKeyErrorif'a'is missing. Create the parent first or usesetdefault(). - Mutating a dictionary while iterating over it. Changing keys during a loop over the same dictionary raises
RuntimeError: dictionary changed size during iteration. Iterate over a copy (list(d.items())) or collect changes and apply them after the loop. - Expecting
setdefault()to overwrite. It only inserts when the key is absent; it never changes an existing value.
Tips
- Use direct assignment for one key and
update()for batches; both are clear and efficient. - For counters, consider
collections.Counterorcollections.defaultdict, which handle missing keys automatically. - When merging dictionaries, remember that later values win. In
d1.update(d2), any shared key takes the value fromd2. - Keep key names consistent. A typo in a string key creates a new entry rather than raising an error, which can be hard to spot later.
- For deeply nested structures, write a small helper function that walks the path and creates missing levels, rather than repeating
setdefault()calls. - Use
copy.deepcopy()when you need an independent nested dictionary; a shallow copy shares inner dictionaries, so updating one affects the other.
Troubleshooting
If your update does not seem to take effect, check whether you are modifying a copy rather than the original. Assignments to a sliced or shallow-copied dictionary do not propagate back. Print id() of both objects if you suspect this.
If you get a KeyError, the key you are reading does not exist. Confirm spelling and case; dictionary keys are case-sensitive. Use in to test membership before reading.
If you get TypeError: 'dict' object is not callable, you likely named a variable dict or used my_dict() instead of my_dict[]. Rename the variable and use square brackets for access.
If update() raises ValueError, the argument is not a sequence of pairs. Convert your data to a list of tuples like [('a', 1), ('b', 2)] before passing it.
If changes disappear after a function call, the function probably modified a local copy. Dictionaries are mutable, so changes inside a function affect the original only if you pass the dictionary itself and mutate it in place, not if you reassign the parameter name.
Frequently Asked Questions
How do I update a value in a dictionary without adding a new key?
Check membership first: if key in d: d[key] = value. This guarantees only existing keys are modified.
What is the difference between update() and direct assignment?
Direct assignment changes one key. update() changes multiple keys at once and accepts a dictionary, keyword arguments, or an iterable of pairs.
Can I update a dictionary value inside a list?
Yes, if the list contains dictionaries: my_list[0]['key'] = value. The list index selects the dictionary, then normal key assignment applies.
Does update() overwrite existing keys?
Yes. Any key present in both the original and the update argument takes the new value. Keys not mentioned remain unchanged.
How do I update a nested dictionary safely?
Use setdefault() to create missing parent keys, or check each level with in before assigning. Avoid chained indexing on keys that may not exist.
Why does my dictionary change when I pass it to a function?
Dictionaries are mutable and passed by reference. A function that mutates the dictionary affects the caller's object. Pass a copy if you need to preserve the original.