To update a dictionary in Python, assign a new value to an existing key with d[key] = value, or merge in another dictionary with d.update(other). Both modify the dictionary in place and return None. If the key does not exist, assignment adds it; if it does, assignment overwrites the old value. That is the whole answer for most cases. The rest of this guide covers the variations that trip people up: nested dictionaries, updating many keys at once, avoiding accidental mutation of the original, and what to do when the update seems to do nothing.
What You'll Need
- Python 3 installed (any recent 3.x version works; the syntax below is standard).
- A way to run Python: the interactive interpreter, a script file, or a notebook.
- A dictionary to work with. You can create one with
d = {'a': 1, 'b': 2}.
Step-by-Step
- Create or identify your dictionary. Open a Python session and define a dictionary, for example
d = {'name': 'Ada', 'age': 36}. Confirm it prints as expected. - Update a single existing key. Assign directly:
d['age'] = 37. This changes the value in place. Printdto confirm the new value appears. - Add a new key with the same syntax.
d['city'] = 'London'adds the key because it did not exist. There is no separate “add” method; assignment handles both cases. - Update several keys at once with
update(). Pass a dictionary:d.update({'age': 38, 'city': 'Paris'}). Existing keys are overwritten, new keys are added. You can also pass keyword arguments:d.update(age=39, country='UK'). Note that keyword keys must be valid identifiers, so string keys containing spaces or hyphens cannot be passed this way. - Update from a list of pairs.
d.update([('age', 40), ('city', 'Rome')])works becauseupdate()accepts any iterable of key-value pairs. This is useful when you build pairs dynamically. - Merge without changing the original. Use the
|operator (Python 3.9 and later):new_d = d | {'age': 41}. The originaldis untouched andnew_dcontains the merged result. The in-place version isd |= {'age': 41}, which does modifyd. - Update a nested dictionary carefully. If , then d['user']['age'] = 37 updates the inner value. Calling replaces the entire inner dictionary, dropping any other keys inside it. To merge nested dictionaries, update the inner one explicitly: d['user'].update({'age': 37}) .
- Update only if the key is missing. Use
setdefault(key, default). It sets the key only when absent and returns the existing value otherwise. For example,d.setdefault('country', 'UK')adds the key if missing but leaves an existing value alone. - Check the result. Print the dictionary or inspect specific keys. Remember that
update()and direct assignment returnNone; do not writed = d.update({...}), because that replaces your dictionary withNone.
Common Mistakes
- Assigning the return value of
update().d = d.update({'a': 1})setsdtoNone. Callupdate()on its own line. - Expecting a new dictionary from
update(). It modifies in place. Use|or{**d, ...}when you need a copy. - Replacing a nested dictionary by accident. Updating a top-level key whose value is a dictionary overwrites the whole inner dictionary. Update the inner dictionary instead.
- Using a mutable default in
setdefault. The default object is created once and shared if reused; use a fresh literal each call or build the value explicitly. - Assuming order changes. Dictionaries preserve insertion order, but updating an existing key keeps its position; adding a new key appends it.
- Mutating a dictionary while iterating over it. Adding or removing keys during a loop raises
RuntimeError: dictionary changed size during iteration. Iterate over a copy withlist(d.items())or build a separate result.
Tips
- Use
d.get(key, default)to read a value without raisingKeyError. - Use
collections.defaultdictwhen every missing key should start with a default value; it avoids repeatedsetdefaultcalls. - For deep merges of nested dictionaries, write a small recursive function or use a dedicated library; the built-in
update()is shallow. - Prefer
|for readable one-line merges in modern Python, andupdate()when you intentionally modify in place. - Keep keys hashable: strings, numbers and tuples work; lists and dictionaries do not.
Troubleshooting
- The dictionary did not change. Check that you called
update()on the dictionary itself, not on a copy. Also confirm you are printing the same object you modified. - You got
TypeError: 'NoneType' object is not subscriptable. You likely assigned the result ofupdate()back to the variable. Re-create the dictionary and callupdate()without assignment. KeyErrorwhen updating nested values. The parent key may not exist yet. Create it first:d.setdefault('user', {}), then update the inner dictionary.RuntimeError: dictionary changed size during iteration. Do not add or delete keys while looping. Iterate overlist(d.items())or collect changes and apply them after the loop.- Unexpected shared data between dictionaries. Copying a dictionary with
dict(d)ord.copy()is shallow; nested dictionaries are still shared. Usecopy.deepcopy(d)when you need fully independent copies. - Keyword arguments rejected.
update(key=value)only accepts identifier-like names. Use a dictionary literal for keys with spaces, hyphens or leading digits.
Frequently Asked Questions
Does dict.update() return a new dictionary?
No. It modifies the dictionary in place and returns None. To get a new dictionary, use the | operator or unpacking such as {**d, 'key': value}.
How do I update a key only if it already exists?
Check with if key in d: before assigning, or use d.get(key) to read the current value. There is no built-in “update only if present” method; the check is the standard approach.
What is the difference between update() and setdefault()?
update() always overwrites existing keys. setdefault() writes only when the key is missing and returns the existing value otherwise.
Can I update a dictionary with another dictionary that has different keys?
Yes. Keys that exist are overwritten; keys that do not exist are added. Nothing is removed.
How do I merge nested dictionaries without losing inner keys?
The built-in update() is shallow, so update the inner dictionary directly, or write a recursive merge that walks both dictionaries and calls update() at each level.
Is dictionary order preserved after an update?
Yes. Updating an existing key keeps its position; adding a new key places it at the end. This behavior is guaranteed in Python 3.7 and later.