Python: Update a Nested Dictionary Safely
In this article
To update a nested dictionary in Python, assign to the full key path directly, for example data['user']['address']['city'] = 'Paris', or use dict.update() with a nested mapping when you want to merge several keys at once. The only catch is that every parent key must already exist; if it does not, Python raises a KeyError. The short fix is to create missing levels first with setdefault() or a small recursive merge function, then write the value. This guide shows the safe patterns, the mistakes that break them, and how to handle deep merges without losing existing data.
What You'll Need
- Python 3 installed (any recent 3.x works; the examples use only the standard library).
- A text editor or IDE, or an interactive Python shell to try the snippets.
- A basic understanding of what a dictionary is and how keys are accessed with square brackets.
- Optional: the
copymodule, which is built in and useful when you need a deep copy before merging.
Step-by-Step
- Start with a nested dictionary. A nested dictionary is simply a dictionary whose values are themselves dictionaries. For example:
data = { 'user': { 'name': 'Ana', 'address': {'city': 'Lisbon', 'zip': '1000'} } } - Update an existing key by chaining the keys. To change the city, walk down each level and assign the new value:
This works because every intermediate key already exists. The assignment replaces only the final value and leaves the rest of the dictionary untouched.data['user']['address']['city'] = 'Porto' - Use
update()to change several keys at one level. If you want to set multiple values inside one nested dictionary, callupdate()on that inner dictionary:
This is equivalent to two separate assignments but reads more cleanly when you have a mapping of new values.data['user']['address'].update({'city': 'Porto', 'zip': '4000'}) - Create missing parent keys with
setdefault(). If you are not sure a level exists,setdefault()returns the existing value or creates it with a default. Chain it to build the path safely:
Eachdata.setdefault('user', {}).setdefault('address', {})['city'] = 'Porto'setdefaultcall returns the inner dictionary, so you can keep chaining. This avoids aKeyErrorwhen a level is missing. - Merge a nested dictionary recursively. When you need to combine two nested dictionaries without overwriting whole branches, write a small recursive function: def deep_update(target, updates): for key, value in updates.items(): if isinstance(value, dict) and isinstance(target.get(key), dict): deep_update(target[key], value) else: target[key] = value return target Call it as . Only the keys you pass are changed; other keys inside address stay as they were.
- Copy first if you need to keep the original. Assignment and update() modify the dictionary in place. If you want a new dictionary and leave the original intact, use copy.deepcopy() before merging: import copy new_data = copy.deepcopy(data) A shallow copy() is not enough for nested dictionaries because the inner dictionaries are still shared.
- Verify the result. Print the dictionary or inspect the specific path to confirm the change landed where you expected:
If the output shows the old value, check that you assigned to the same object you are printing and that no later code overwrote it.print(data['user']['address'])
Common Mistakes
- Assigning to a missing parent.
data['user']['phone']['home'] = '555'raisesKeyError: 'phone'ifphonedoes not exist. Create the level first withsetdefaultor a merge function. - Using update() and expecting a deep merge. replaces the entire user dictionary, deleting name and any other keys. Use a recursive merge when you want to preserve siblings.
- Relying on a shallow copy.
new = data.copy()then changingnew['user']['address']['city']also changes the original, because the inner dictionaries are the same objects. Usecopy.deepcopy(). - Mutating a dictionary while iterating over it. Adding or deleting keys during a
forloop over the same dictionary raisesRuntimeError: dictionary changed size during iteration. Collect the changes first, then apply them. - Confusing keys and values. A nested dictionary is keyed by strings (or other hashable objects), not by position. There is no index like a list, so
data[0]only works if0is an actual key.
Tips
- Use
collections.defaultdict(dict)when you are building a nested structure from scratch; it creates missing levels automatically on access. - Prefer
deep_updateover manual chained assignments when the update comes from user input or a config file, because the shape of the incoming data may vary. - Keep a clear naming convention for your nested keys so the path is readable in code, for example
config['network']['wifi']['ssid']. - If you only need to read a value and it may be missing, use
data.get('user', {}).get('address', {}).get('city')to avoid exceptions. - Write a quick test with
assertafter updating, such asassert data['user']['address']['city'] == 'Porto', to catch silent overwrites.
Troubleshooting
If you get a KeyError, the parent path does not exist. Print the dictionary at each level to see where it stops, then add the missing level with setdefault or your merge function. If the value does not change, confirm you are modifying the same object you later read; reassigning a variable to a new dictionary breaks the link. If unrelated keys disappear after an update, you probably used update() where a deep merge was needed. If changes appear in an object you thought was a copy, switch to copy.deepcopy(). If you see RuntimeError: dictionary changed size during iteration, build a list of changes and apply them after the loop. If the structure is unexpectedly a list instead of a dictionary, check the source data; indexing with a string on a list raises TypeError, so inspect the type with type(data['user']) before assigning.
Frequently Asked Questions
How do I update a nested dictionary without overwriting other keys?
Use a recursive merge function that checks whether both the target and the incoming value are dictionaries. If they are, recurse into them; otherwise assign the new value. A plain update() replaces the whole branch.
What is the difference between setdefault and update for nested dictionaries?
setdefault creates a key with a default value only if it is missing and returns the value, which makes it useful for building paths. update merges a mapping into an existing dictionary at one level and does not create parent levels for you.
Why does my nested dictionary update change the original too?
Because a shallow copy shares the inner dictionaries. Use copy.deepcopy() to get an independent nested structure before modifying it.
Can I update a nested dictionary with a dot path like 'user.address.city'?
Not with plain dictionaries. You would need to split the path on dots and walk the keys one by one, or use a third-party library that supports dotted access. The standard library does not include that feature.
How do I add a new nested key safely?
Chain setdefault calls for each missing level, then assign the final key. For example, data.setdefault('user', {}).setdefault('phone', {})['home'] = '555' creates the levels as needed.
Does dict.update() work recursively?
No. update() is shallow: it replaces top-level values, and if a value is itself a dictionary, that whole dictionary replaces the existing one rather than merging into it.