Python Reference ยท Dictionaries and Sets
Python dict.update() method
Reference for Python dict.update(): merge another mapping, pairs or keyword arguments into a dictionary in place, overwriting keys, with return value None.
The update() method copies key-value pairs into a dictionary, in place. Existing keys get the new value; new keys are added. The source can be another dictionary, any iterable of key-value pairs, or keyword arguments.
Because it overwrites, the last value wins. update() returns None, which catches many people out: d = d.update(x) throws your dictionary away.
settings = {"theme": "dark"} settings.update({"font": "mono"}, size=14) # {'theme': 'dark', 'font': 'mono', 'size': 14}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
dict.update(other) dict.update(iterable_of_pairs) dict.update(**kwargs)
| Name | Description |
|---|---|
other |
A mapping (or object with a keys() method) whose items are copied in. |
iterable_of_pairs |
An iterable of two-item iterables such as [("a", 1), ("b", 2)]. |
**kwargs |
Keyword arguments; the names become string keys. |
Return value: None.
Raises: TypeError for unhashable keys; ValueError if an element of an iterable is not a pair.
Usage notes
- It mutates the dictionary and returns
None. To get a merged copy without changing either source, usea | b(Python 3.9+) or{**a, **b}. - Later values win. With several sources in one call, keyword arguments are applied after the positional one.
- Shallow copy. Values are not copied; nested dictionaries and lists are shared and replaced as a whole.
- Keyword arguments only work for keys that are valid identifiers and become strings. Use a dict for other keys.
- Insertion order: new keys go at the end; overwriting a key keeps its original position.
- Updating while iterating over the same dictionary can raise
RuntimeError: dictionary changed size during iteration.