Python Dictionary Update Method: How to Use It
In this article
The update() method in Python modifies a dictionary in place by adding new key-value pairs or overwriting existing ones. It accepts either another dictionary, an iterable of key-value pairs, or keyword arguments, and returns None. Nothing needs to be installed first—any standard Python 3 installation includes it.
What You'll Need
- A working Python 3 installation (any recent version;
update()has been stable for years). - A text editor or IDE to write and run your script.
- Basic familiarity with creating dictionaries and accessing keys.
Step-by-Step
- Create a dictionary. Start with a simple dictionary you want to modify. For example:
inventory = {"apples": 10, "bananas": 5} - Decide what to update. You can add new keys, change existing values, or both. The
update()method takes a single argument that can be another dictionary, an iterable of key-value pairs (like a list of tuples), or keyword arguments. - Call
update()with a dictionary. Pass a dictionary containing the changes:
After this call,inventory.update({"bananas": 8, "oranges": 12})inventorybecomes{"apples": 10, "bananas": 8, "oranges": 12}. The existing key"bananas"is overwritten with the new value, and"oranges"is added. - Call
update()with an iterable of pairs. You can pass a list of two-item tuples:
Each tuple's first element becomes a key, the second its value.inventory.update([("pears", 7), ("grapes", 20)]) - Call
update()with keyword arguments. Use keyword arguments for string keys:
This adds or updates keysinventory.update(kiwis=3, lemons=9)"kiwis"and"lemons". Note that keyword arguments only work for keys that are valid Python identifiers (strings without spaces or special characters). - Check the result. Print the dictionary to confirm the changes:
The output shows all keys with their latest values.print(inventory) - Understand the return value.
update()modifies the dictionary in place and returnsNone. Do not assign its result to a variable expecting a new dictionary; the original dictionary is changed. - Handle duplicate keys. If the argument contains a key already in the dictionary, the old value is replaced. No error is raised. This is the intended behavior.
- Use
update()with multiple sources. You can chain updates or pass a dictionary and keyword arguments together? Actually,update()accepts only one positional argument, but you can call it multiple times or combine sources beforehand. For example:inventory.update({"plums": 4}) inventory.update(apricots=6)
Common Mistakes
- Expecting a new dictionary.
update()returnsNone; assigningnew_dict = old_dict.update({...})leavesnew_dictasNone. Usedict.copy()first if you need a separate result. - Passing an invalid iterable. If you pass a list of items that are not pairs (e.g., single values or tuples of length other than two), Python raises
ValueErrororTypeError. Ensure each element has exactly two items. - Using non-string keys with keyword arguments. Keyword arguments only create string keys. To add integer keys, use a dictionary or iterable of pairs.
- Forgetting that keys are case-sensitive.
"Apple"and"apple"are different keys; updating one does not affect the other. - Modifying a dictionary while iterating over it. Calling
update()inside a loop that iterates over the same dictionary can cause aRuntimeError. Collect changes first, then apply them after the loop.
Tips
- Use
update()to merge configuration dictionaries or apply defaults. For example, start with default settings and update with user-provided options. - If you need to merge without modifying the original, create a copy:
merged = original.copy(); merged.update(changes). - For Python 3.9+, the
|operator (merge) and|=(update) offer a concise alternative, butupdate()works in all Python 3 versions. - Remember that
update()is shallow: it replaces values at the top level but does not recursively merge nested dictionaries. - Use
update()withzip()to combine two lists into key-value pairs:d.update(zip(keys, values)).
Troubleshooting
- TypeError: 'int' object is not iterable. You passed a non-iterable argument. Check that you are passing a dictionary, list of pairs, or keyword arguments.
- ValueError: dictionary update sequence element #0 has length X; 2 is required. One of the elements in your iterable does not have exactly two items. Inspect the iterable and ensure each element is a pair.
- KeyError when updating with a dictionary. This should not happen with
update(); if you see aKeyError, you may be using a different method or accessing a missing key elsewhere. - Unexpected None result. If you assigned the result of
update(), you gotNone. Use the original dictionary variable instead. - Changes not appearing. Ensure you are modifying the same dictionary object. If you passed a copy, the original remains unchanged.
- RuntimeError: dictionary changed size during iteration. Do not call
update()while iterating over the dictionary. Build a separate dictionary of changes and apply after the loop.
Frequently Asked Questions
Does update() overwrite existing keys?
Yes. If a key already exists in the dictionary, its value is replaced with the new value from the argument.
Can I use update() to add multiple key-value pairs at once?
Yes. Pass a dictionary or an iterable of pairs containing multiple entries; all are added or updated in one call.
What happens if I pass a list of tuples with duplicate keys?
The last occurrence wins. The dictionary will contain the value from the final tuple with that key.
Is update() available in Python 2?
Yes, but Python 2 is end-of-life. The method works similarly, though keyword argument behavior may differ slightly. Use Python 3 for current projects.
Can I update a dictionary with another dictionary that has nested dictionaries?
Yes, but the update is shallow: the entire nested dictionary is replaced, not merged. To merge nested dictionaries, you need a recursive function or a library like mergedeep.
Does update() preserve the order of keys?
In Python 3.7+, dictionaries maintain insertion order. Existing keys keep their position; new keys are added at the end. Overwriting a value does not change key order.