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
Example
#profile = {"name": "Emma", "level": 3, "theme": "light"}
profile.update({"level": 4, "streak": 12})
print(profile)
profile.update(theme="dark")
print(profile)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
#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
#defaults = {"theme": "dark", "lang": "en", "sound": True}
user = {"lang": "fr", "sound": False}
settings = defaults | user
print(settings)
print(defaults)stats = {"exp": 100}
result = stats.update(exp=150)
print(result)
print(stats)Good practices
#- Don't assign the result of the method:
d = d.update(...)turns the dictionary intoNone. Callupdate()as its own statement. - When the original must stay unchanged, create a new dictionary with
a | bor{**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
#- dict.setdefault()Returns the value of a key, and first stores a default value in the dictionary when the key is missing.
- dict.pop()Removes a key from a dictionary and returns its value, optionally with a fallback value.
- dict()Creates a dictionary from key-value pairs or keyword arguments.
- Dict comprehensionsA concise way to build a new dictionary by transforming or filtering another collection.
- list.extend()Adds all the items of another collection to the end of a list.
Spotted a mistake or missing an example? Write to us.