dict.update()

Adds pairs from another dictionary or from arguments to a dictionary, overwriting existing keys.

Returns
None (the dictionary changes in place).
Changes the original
Yes
On this page

Example

#
Python
profile = {"name": "Emma", "level": 3, "theme": "light"}

profile.update({"level": 4, "streak": 12})
print(profile)

profile.update(theme="dark")
print(profile)
Resultsaved result, you can check it
{'name': 'Emma', 'level': 4, 'theme': 'light', 'streak': 12}
{'name': 'Emma', 'level': 4, 'theme': 'dark', 'streak': 12}

Definition and usage

#

The update() method adds every pair from a given dictionary, list of pairs, or keyword arguments to the dictionary. If a key already exists, its value is replaced with the new one. The dictionary changes in place, and the method returns None.

Typical uses are layering user settings on top of defaults, and changing several fields of a record at once instead of assigning them one by one.

Since Python 3.9, operators are also available: a | b creates a new, merged dictionary without changing the originals, and a |= b works like update(). When keys conflict, the value from the right side always wins.

Syntax

#
Syntax
dict.update(other)
dict.update(key=value, …)

Parameters

#
  • other

    a dictionary or collection of pairs, optional

    The source of the new key-value pairs.
  • **kwargs

    optional

    Pairs given as keyword arguments, e.g. level=4.

More examples

#
Default settings and the | operator
Python
defaults = {"theme": "dark", "lang": "en", "sound": True}
user = {"lang": "fr", "sound": False}

settings = defaults | user
print(settings)
print(defaults)
Resultsaved result, you can check it
{'theme': 'dark', 'lang': 'fr', 'sound': False}
{'theme': 'dark', 'lang': 'en', 'sound': True}
Trap: update() returns None
Python
stats = {"exp": 100}
result = stats.update(exp=150)

print(result)
print(stats)
Resultsaved result, you can check it
None
{'exp': 150}

Good practices

#
  • Don't assign the result of the method: d = d.update(...) turns the dictionary into None. Call update() as its own statement.
  • When the original must stay unchanged, create a new dictionary with a | b or {**a, **b}.
  • The merge is shallow: a nested dictionary on the right replaces the whole nested dictionary on the left instead of merging into it.

Related entries

#

Spotted a mistake or missing an example? Write to us.