The update() method in a Python dictionary merges keys and values from another dictionary, an iterable of key-value pairs, or keyword arguments into the existing dictionary, overwriting any keys that already exist. For example, d.update({'b': 2}) adds key 'b' or changes its value if it already exists.
What Does update() Do Exactly?
When you call dict.update(), it takes one argument (or none) and adds or replaces entries in the original dictionary. The method modifies the dictionary in place and returns None—it does not create a new dictionary. If you need a new dictionary without altering the original, use the | operator (Python 3.9+) or {**d1, **d2}.
Here is a minimal example:
d = {'a': 1}
d.update({'b': 2})
print(d) # {'a': 1, 'b': 2}
If the argument contains a key that already exists, the old value is replaced:
d = {'a': 1}
d.update({'a': 99})
print(d) # {'a': 99}
How to Use update() with Different Input Types
The update() method accepts three main forms of input:
- Another dictionary –
d.update(other_dict)merges all key-value pairs. - An iterable of key-value pairs – such as a list of tuples:
d.update([('x', 1), ('y', 2)]). - Keyword arguments –
d.update(x=1, y=2)adds keys as strings (keys must be valid Python identifiers).
You can also mix these in one call, but only one positional argument is allowed. For example:
d = {}
d.update({'a': 1}, b=2) # Works: positional dict + keyword args
print(d) # {'a': 1, 'b': 2}
If you pass an iterable of pairs, each element must itself be an iterable of length 2 (like a tuple or list). Otherwise, Python raises a ValueError.
Real-World Examples and Use Cases
Updating dictionaries is common when merging configuration settings, combining user input with defaults, or updating state in a loop.
Example 1: Merging configuration defaults
defaults = {'theme': 'dark', 'lang': 'en'}
user_prefs = {'lang': 'fr'}
defaults.update(user_prefs)
print(defaults) # {'theme': 'dark', 'lang': 'fr'}
Example 2: Updating from a list of pairs
data = [('name', 'Alice'), ('age', 30)]
person = {}
person.update(data)
print(person) # {'name': 'Alice', 'age': 30}
Example 3: Using keyword arguments for simple updates
counter = {'count': 0}
counter.update(count=1)
print(counter) # {'count': 1}
Note that keyword arguments always create string keys, so you cannot use them for non-string keys like integers.
Common Mistakes and Pitfalls
One frequent mistake is expecting update() to return the updated dictionary. It returns None, so chaining like d.update(x=1).update(y=2) will fail with an AttributeError.
Another pitfall is accidentally overwriting data. Since update() replaces existing keys, be sure that is the intended behavior. If you want to keep the original values and only add missing keys, use setdefault() in a loop or a dictionary comprehension.
Also, when using an iterable of pairs, ensure each pair has exactly two elements. For example, d.update([('a', 1, 2)]) raises ValueError: dictionary update sequence element #0 has length 3; 2 is required.
Finally, remember that update() works on the dictionary in place—it does not create a copy. If you need a copy, do new_dict = original.copy() first, then update the copy.
Alternatives to update() in Python
Depending on your Python version and needs, there are other ways to merge dictionaries:
- Dictionary unpacking –
{**d1, **d2}creates a new dictionary (Python 3.5+). - Union operator –
d1 | d2creates a new dictionary (Python 3.9+). - In-place union –
d1 |= d2updatesd1in place (Python 3.9+). - Loop with assignment – for full control, iterate and assign each key.
Here is a comparison:
d1 = {'a': 1}
d2 = {'b': 2}
merged = d1 | d2 # {'a': 1, 'b': 2}
d1 |= d2 # d1 becomes {'a': 1, 'b': 2}
The | operator is often more readable than update() when you want a new dictionary, but update() remains the standard for modifying an existing dictionary.
How update() Works in Other Languages
Many other languages have similar methods for merging dictionaries:
- JavaScript –
Object.assign(target, source)or the spread operator{...target, ...source}. - Java –
Map.putAll(otherMap). - C# – No direct method, but you can loop or use LINQ’s
ToDictionary. - Ruby –
merge!(destructive) ormerge(non-destructive).
In all cases, the behavior is similar: existing keys are overwritten, new keys are added. The main difference is whether the original object is modified or a new one is returned.
Performance and When to Use update()
update() is implemented in C and is generally very fast for merging large dictionaries. It is O(n) where n is the number of items in the argument. For small dictionaries, any method is fine.
Use update() when you already have a dictionary and want to modify it in place. This is common in loops where you accumulate results, or when updating a configuration object. Avoid using it in a loop that repeatedly updates the same dictionary with a large number of items—consider building a new dictionary instead if performance is critical.
One performance tip: if you are updating with many key-value pairs, passing a dictionary is faster than passing a list of tuples, because the dictionary is already hashed.
Frequently Asked Questions
Does update() return a new dictionary?
No, update() modifies the original dictionary in place and returns None. If you need a new dictionary, use the | operator or dictionary unpacking.
Can I use update() with keyword arguments?
Yes, you can pass keyword arguments like d.update(a=1, b=2). The keys will be strings. This is a convenient way to add a few known keys.
What happens if I update with an empty dictionary?
Nothing changes. The original dictionary remains exactly the same, and no error is raised.
How do I update a dictionary without overwriting existing keys?
Use a loop with setdefault() or check for key existence. For example:
for k, v in new_items.items():
d.setdefault(k, v)
This only sets the value if the key is not already present.
Is update() available in Python 2?
Yes, update() has existed since Python 2.4 and works the same way. However, Python 2 is end-of-life, so use Python 3 for new code.
Can I update a dictionary with a list of two-element lists?
Yes, any iterable of key-value pairs works. For example, d.update([['a', 1], ['b', 2]]) is valid.
Related
- Useful MacOS Shortcuts: 40+ You’ll Actually Use
- What Is enum in Java? Definition & Usage
- How to Update a Dictionary in Python
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Find a Table in Excel: Search and NavigationTo find a table in Excel, search for a word or value you expect it to contain, then…
- How to Share an Excel Workbook in Windows 11 SafelyTo share an Excel workbook in Windows 11, save it to OneDrive or SharePoint, select Share in Excel,…
- How to Delete a Full Page in Word: Step-by-StepTo delete a full page in Word, click anywhere on that page, open Go To, enter \page, and…
- GL Wand Excel Not Responding: Causes and Fixes to TryIf GL Wand makes Excel show “Not Responding,” first stop clicking and give the current operation a little…
- Excel Hide Columns When Printing Without Changing DataExcel does not have a separate print-only hidden setting for a column: hiding a column on a worksheet…
- Excel Import CSV Into a New Tab: Steps, Tips, and FixesTo import a CSV file into a new tab in Excel for Microsoft 365 on Windows, select Data…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.