Python Dictionary Update: How to Use It
In this article
The dict.update() method merges another dictionary or an iterable of key-value pairs into an existing dictionary. It modifies the dictionary in place and returns None. If a key already exists, its value is overwritten; if not, the key is added. You need only a Python interpreter (version 3.x) and a basic understanding of dictionaries.
What You'll Need
- Python 3 installed on your computer (any recent version).
- A text editor or IDE to write and run Python code.
- Basic familiarity with Python dictionaries and key-value pairs.
Step-by-Step
- Create a dictionary. Start with an existing dictionary that you want to update. For example:
my_dict = {'a': 1, 'b': 2} - Prepare the update data. You can update with another dictionary, an iterable of key-value pairs (like a list of tuples), or keyword arguments. For example:
new_data = {'b': 3, 'c': 4} - Call
update()on the original dictionary. Pass the new data as an argument:my_dict.update(new_data) - Check the result. The original dictionary now contains the merged data. Print it to verify:
Note that the value for keyprint(my_dict) # Output: {'a': 1, 'b': 3, 'c': 4}'b'was overwritten from 2 to 3, and key'c'was added. - Update using an iterable of pairs. You can also pass a list of tuples:
This adds keysmy_dict.update([('d', 5), ('e', 6)])'d'and'e'with values 5 and 6. - Update using keyword arguments. For string keys, you can use keyword arguments directly:
This adds keysmy_dict.update(f=7, g=8)'f'and'g'. Note that keyword arguments are always strings. - Understand the return value.
update()returnsNone. Do not assign its result to a variable expecting the updated dictionary. The original dictionary is modified in place.
Common Mistakes
- Assigning the result of
update(). Writingmy_dict = my_dict.update(new_data)setsmy_dicttoNone. Always callupdate()without assignment. - Expecting a new dictionary.
update()modifies the original dictionary; it does not create a copy. If you need a new dictionary, use{**my_dict, **new_data}ormy_dict.copy()then update. - Passing an invalid iterable. The argument must be a mapping or an iterable of key-value pairs. Passing a list of single values or a string will raise a
ValueErrororTypeError. - Using non-string keys with keyword arguments. Keyword arguments only work for string keys. For other key types, use a dictionary or list of tuples.
- Forgetting that keys are overwritten. Existing keys are replaced, not merged. If you need to combine values, you must handle that manually.
Tips
- Use
update()to merge configuration dictionaries or apply default settings. - To avoid modifying the original, create a copy first:
new_dict = my_dict.copy(); new_dict.update(other). - For Python 3.9+, you can use the merge operator
|to create a new dictionary:merged = my_dict | new_data. This does not modify the originals. - When updating with multiple sources, you can chain
update()calls or pass multiple arguments? Actually,update()takes at most one positional argument, but you can pass keyword arguments alongside. For multiple dictionaries, callupdate()sequentially. - Remember that
update()is shallow: nested dictionaries are replaced entirely, not merged recursively.
Troubleshooting
- TypeError: 'NoneType' object is not subscriptable — You assigned the result of
update()to a variable. Remove the assignment. - ValueError: dictionary update sequence element #0 has length X; 2 is required — The iterable you passed does not contain key-value pairs. Ensure each element is a tuple or list of two items.
- TypeError: cannot convert dictionary update sequence element #0 to a sequence — You passed a non-iterable or an iterable of non-iterables. Check the argument type.
- Unexpected overwrites — If you did not want to overwrite existing keys, check the keys in the update data before calling
update(), or use a loop withsetdefault(). - Modifying a dictionary while iterating — Avoid calling
update()on a dictionary while iterating over it; this can raise aRuntimeError. Iterate over a copy instead.
Frequently Asked Questions
Does dict.update() return a new dictionary?
No, it modifies the dictionary in place and returns None.
Can I update a dictionary with a list of tuples?
Yes, as long as each tuple contains exactly two elements: a key and a value.
What happens if the key already exists?
The existing value is overwritten with the new value.
Can I use update() with keyword arguments?
Yes, but only for string keys. For example: my_dict.update(key=value).
Is update() the same as merging with |?
No, | creates a new dictionary, while update() modifies the original in place.
How do I merge dictionaries without overwriting?
Use a loop with setdefault() or check keys before updating. For example: for k, v in other.items(): my_dict.setdefault(k, v).