The dict.update() method merges keys and values from another dictionary, an iterable of key-value pairs, or keyword arguments into the original dictionary, overwriting any existing keys. For example, d = {'a': 1}; d.update({'b': 2}) leaves d as {'a': 1, 'b': 2}. It modifies the dictionary in place and returns None.
What the update method does
update() is a built-in method of Python dictionaries (available since Python 2.4). It takes one argument, which can be any of three forms:
- Another dictionary – e.g.,
d.update(other_dict) - An iterable of key-value pairs – e.g., a list of tuples like
[('x', 1), ('y', 2)] - Keyword arguments – e.g.,
d.update(x=1, y=2)
If a key already exists in the original dictionary, its old value is replaced. If the key is new, it is added. The method returns None, so it cannot be chained like d.update(...).something().
How to use it: syntax and examples
The simplest usage is merging another dictionary:
d = {'a': 1, 'b': 2}
d.update({'b': 3, 'c': 4})
print(d) # {'a': 1, 'b': 3, 'c': 4}
You can also pass an iterable of tuples:
d = {}
d.update([('x', 10), ('y', 20)])
print(d) # {'x': 10, 'y': 20}
And keyword arguments work as well, but keys must be valid Python identifiers (no spaces, no dashes):
d = {}
d.update(name='Alice', age=30)
print(d) # {'name': 'Alice', 'age': 30}
You can even mix forms – the method accepts one positional argument and any number of keyword arguments. For instance, d.update({'a': 1}, b=2) works.
How update works under the hood
Internally, update() iterates over the provided source. For a dictionary, it iterates over its keys and uses __getitem__ to fetch values. For an iterable of pairs, it unpacks each pair into a key and value. For keyword arguments, it treats them as a mapping. The method then assigns each key-value pair using the dictionary’s __setitem__, which overwrites existing keys. This is why the operation is O(n) where n is the number of items in the source. The method is implemented in C (in CPython) for efficiency, so it’s generally faster than a manual loop.
When to use update vs other methods
Python offers several ways to combine dictionaries. Choose based on whether you need to mutate the original or create a new one:
- Use
update()when you want to modify an existing dictionary in place (e.g., in a loop or when building a config object). - Use the
|operator (Python 3.9+) to create a new merged dictionary:merged = d1 | d2. This does not change either original. - Use
{**d1, **d2}(Python 3.5+) to create a new dictionary with keys from both, later keys overwriting earlier ones. - Use
dict(d1, **d2)as another way to create a new dictionary, but note thatd2‘s keys must be strings (since they are passed as keyword arguments).
If you need to update only if the key doesn’t exist, consider setdefault() or a conditional check. For multiple dictionaries, update() can be chained in a loop.
Common pitfalls and misconceptions
One frequent mistake is expecting update() to return the updated dictionary. It returns None, so code like new_dict = old_dict.update(other) will set new_dict to None. Another misconception is that update() creates a copy – it does not; it modifies the original. If you need a copy, do new_dict = original.copy() then new_dict.update(other).
Also, when using keyword arguments, keys are converted to strings only if they are not already strings? Actually, keyword arguments are always treated as string keys. For example, d.update(1=2) is a syntax error because 1 is not a valid identifier. Use a dictionary or iterable for non-string keys.
Performance and memory considerations
update() is efficient for merging large dictionaries because it is implemented in C. However, if you are updating in a tight loop with many small updates, consider building a list of pairs and updating once. Memory-wise, update() does not create a new dictionary, so it uses less memory than creating a merged copy. But if you need to keep the original unchanged, you must copy it first, which doubles memory usage temporarily.
Alternatives and related methods
Besides update(), Python dictionaries have other methods that modify or combine:
setdefault(key, default)– sets the key to the default only if it doesn’t exist, then returns the value.pop(key, default)– removes and returns the value; raises KeyError if missing and no default.clear()– removes all items.copy()– returns a shallow copy.
For merging without mutation, the | operator and dictionary unpacking are more concise and readable in modern Python. For example, merged = {**base, **overrides} is a common idiom for applying defaults.
Frequently Asked Questions
Does dict.update() return a new dictionary?
No. It modifies the dictionary in place and returns None. If you need a new dictionary, use the | operator or dictionary unpacking, or copy first.
Can I use update() with keyword arguments?
Yes, but the keys must be valid Python identifiers (e.g., update(a=1)). To use keys with spaces or dashes, pass a dictionary or an iterable of pairs.
What happens if a key exists in both dictionaries?
The value from the argument passed to update() overwrites the original value. For example, d = {'a': 1}; d.update({'a': 2}) results in {'a': 2}.
Is update() the same as the | operator?
No. update() modifies the original dictionary, while | creates a new dictionary. Also, | was added in Python 3.9, so older versions only have update().
Can I update a dictionary from a list of tuples?
Yes, pass a list of two-element tuples (or any iterable of pairs) as the argument. For example, d.update([('a', 1), ('b', 2)]).
Why does update() return None?
It follows the Python convention that mutating methods return None (like list.append()). This prevents confusion about whether the original or a copy is returned.
Related
- Data Entry How to Do: Steps, Tools, and Accuracy Tips
- How to Select All Files in a Folder (Windows & Mac)
- Select All Cells in a Range: Excel & Sheets
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Consolidate Rows With the Same ValueYes. To consolidate rows that share a value in Excel, summarize them with a PivotTable or Power Query’s…
- How to Insert a Page Border in Excel for Printed SheetsExcel has no built-in page-border command like Word. To add a border to a printed sheet, draw a…
- Today in Google Sheets: How the TODAY Function WorksTo show today’s date in Google Sheets, enter =TODAY() in a cell and press Enter. The function returns…
- Excel Keyboard Shortcut for Inserting Copied CellsIn Excel for Microsoft 365 on Windows, copy the cells with Ctrl+C, select the cell where the copied…
- By Means of an Update? Meaning & Real Usage“By means of an update?” is a question that asks whether a change or new information is delivered…
- How to Repair an Excel File in Windows 11To repair an Excel file in Windows 11, first make a copy of it, then open Excel and…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.