Update Dictionary with New Values in Python
In this article
To update a dictionary with new values in Python, use the update() method with a second dictionary or an iterable of key-value pairs, or assign directly to a key with d[key] = value. Both are built-in, need no imports, and work in every current Python 3 version. The update() method is the cleanest choice when you have several new values at once; direct assignment is best for a single key. This guide walks through the exact syntax, the cases where the two approaches behave differently, and the errors you are most likely to hit.
What You'll Need
- Python 3 installed and working (any recent 3.x release is fine; the dictionary methods used here have been stable for years).
- A way to run Python: the interactive interpreter, a saved
.pyfile, or a notebook. - A dictionary you want to modify, or a few lines of code to create one for practice.
Step-by-Step
- Create or identify your dictionary. For example:
scores = {"alice": 10, "bob": 7}. If you are working with an existing dictionary, print it first so you know its current contents. - Decide whether you are adding new keys, changing existing ones, or both. The syntax is the same, but the result differs: adding creates a new entry, changing overwrites the old value.
- For a single key, assign directly. Write
scores["carol"] = 12to add a new key, orscores["alice"] = 15to replace an existing value. This is the fastest, most readable option for one update. - For several keys at once, call
update()with a dictionary. Writescores.update({"bob": 9, "dave": 4}). Existing keys are overwritten and new keys are added in one call. - Alternatively, pass keyword arguments to
update(). Writescores.update(carol=12, dave=4). This only works when the keys are valid Python identifiers (letters, digits, underscores, not starting with a digit). For keys with spaces, hyphens, or other characters, use the dictionary form instead. - Or pass an iterable of pairs. Write
scores.update([("carol", 12), ("dave", 4)]). A list of two-item tuples, a list of two-item lists, or a generator of pairs all work. This is useful when your new values come from a loop or a query result. - Check the result. Print the dictionary:
print(scores). Confirm that existing keys now hold the new values and that new keys appear. Remember thatupdate()returnsNoneand changes the dictionary in place; do not assign its return value to a variable. - If you want a new dictionary instead of modifying the original, use
{**scores, "carol": 12}orscores | {"carol": 12}(the|merge operator requires Python 3.9 or later). Both create a fresh dictionary and leave the original untouched.
Common Mistakes
- Assigning the result of
update().scores = scores.update({...})setsscorestoNone. Callupdate()on its own line. - Using keyword arguments for non-identifier keys.
d.update({"first name": "Ann"})works;d.update(first name="Ann")is a syntax error. Use the dictionary form for keys with spaces or special characters. - Passing a plain list of values.
d.update([1, 2, 3])raisesValueErrorbecause each item must be a key-value pair. Wrap each value in a tuple. - Forgetting that
update()overwrites silently. If you need to keep existing values, check withif key not in dbefore assigning, or used.setdefault(key, value), which only sets the value when the key is missing. - Mutating a dictionary while iterating over it. Adding or removing keys inside a
for key in d:loop raisesRuntimeError: dictionary changed size during iteration. Iterate overlist(d.items())or build a separate list of updates and apply them after the loop. - Assuming nested dictionaries merge deeply.
update()replaces a nested dictionary wholesale, not key by key. If you need a deep merge, handle the nested levels explicitly.
Tips
- Use
d.update()when you have a batch of changes; used[key] = valuefor one-off edits. Mixing the two in the same function is normal and readable. - To update only missing keys, loop with
setdefault()or check membership first. This is the closest built-in equivalent to a "fill in the blanks" update. - If the new values come from another dictionary you do not want to modify,
update()does not alter the source dictionary; it only reads from it. - For a copy-then-update pattern,
new = old.copy(); new.update(changes)is explicit and works on all Python 3 versions, including those before 3.9 where the|operator is unavailable. - When keys are user-supplied strings, normalise them (for example with
.strip().lower()) before updating so you do not end up with near-duplicate keys that look the same but are not.
Troubleshooting
TypeError: 'NoneType' object is not subscriptableafter an update: you assigned the return value ofupdate(). Remove the assignment and callupdate()as a statement.ValueError: dictionary update sequence element #0 has length ...: the iterable you passed does not contain two-item pairs. Convert each item to a tuple or pass a dictionary instead.TypeError: cannot convert dictionary update sequence element ...: same cause; check that every element is a pair, not a bare value.- Updates appear to do nothing: confirm you are printing the same object you updated, and that you did not create a copy with
copy()or a comprehension and then update the original. RuntimeError: dictionary changed size during iteration: collect your changes in a separate list or dictionary, then apply them after the loop finishes.- Unexpected key values: print
d.keys()and compare with the keys you passed. Whitespace, case differences, and numeric strings versus integers are the usual culprits.
Frequently Asked Questions
Does update() replace existing keys?
Yes. If a key already exists, its value is overwritten with the new one. New keys are added alongside the existing ones.
What is the difference between update() and direct assignment?
Direct assignment sets one key. update() applies many key-value pairs in a single call. The overwrite behaviour is the same for keys that already exist.
Can I update a dictionary with a list of tuples?
Yes. Pass any iterable of two-item pairs, such as d.update([("a", 1), ("b", 2)]). Each pair must contain exactly two items.
How do I update only keys that are missing?
Use d.setdefault(key, value) for each key, or check if key not in d before assigning. Plain update() always overwrites.
Does update() modify the dictionary passed to it?
No. The source dictionary is only read. The dictionary you call update() on is the one that changes.
How do I merge two dictionaries without changing either?
Use {**a, **b}, or a | b on Python 3.9 and later. Both return a new dictionary; the originals stay as they were.