Videos
for example, you have a dictionary 'DictA' and you want to update it with all the items from 'DictB'. Instead of looping on the keys, or items of DictB, you can simply:
DictA |= DictB
I use this A LOT, and I'm thankful to the Redditor who mentioned it in one of those long 'share your tips' threads...
Python has this feature built-in:
>>> d = {'b': 4}
>>> d.update({'a': 2})
>>> d
{'a': 2, 'b': 4}
Or given you're not allowed to use dict.update:
>>> d = dict(d.items() + {'a': 2}.items()) # doesn't work in python 3
With python 3.9 you can use an |= update operator:
>>> d = {'b': 4}
>>> d |= {'a': 2}
>>> d
{'a': 2, 'b': 4}
1. You can update many keys on the same statement.
my_dict.update(other_dict)
In this case you don't have to know how many keys are in the other_dict. You'll just be sure that all of them will be updated on my_dict.
2. You can use any iterable of key/value pairs with dict.update
As per the documentation you can use another dictionary, kwargs, list of tuples, or even generators that yield tuples of len 2.
3. You can use the update method as an argument for functions that expect a function argument.
Example:
def update_value(key, value, update_function):
update_function([(key, value)])
update_value("k", 3, update_on_the_db) # suppose you have a update_on_the_db function
update_value("k", 3, my_dict.update) # this will update on the dict
d.update(n) is basically an efficient implementation of the loop
for key, value in n.items():
d[key] = value
But syntactically, it also lets you specify explicit key-value pairs without building a dict, either using keyword argumetns
d.update(a=1, b=2)
or an iterable of pairs:
d.update([('a', 1), ('b', 2)])
The difference is that the second method does not work:
>>> {}.update(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: update expected at most 1 arguments, got 2
dict.update() expects to find a iterable of key-value pairs, keyword arguments, or another dictionary:
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return
None.
update()accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs:d.update(red=1, blue=2).
map() is a built-in method that produces a sequence by applying the elements of the second (and subsequent) arguments to the first argument, which must be a callable. Unless your key object is a callable and the value object is a sequence, your first method will fail too.
Demo of a working map() application:
>>> def key(v):
... return (v, v)
...
>>> value = range(3)
>>> map(key, value)
[(0, 0), (1, 1), (2, 2)]
>>> product = {}
>>> product.update(map(key, value))
>>> product
{0: 0, 1: 1, 2: 2}
Here map() just produces key-value pairs, which satisfies the dict.update() expectations.
- Python 3.9 and PEP 584 introduces the
dict union, for updating onedictfrom anotherdict.- Dict union will return a new
dictconsisting of the left operand merged with the right operand, each of which must be adict(or an instance of adictsubclass). If a key appears in both operands, the last-seen value (i.e. that from the right-hand operand) wins.
- Dict union will return a new
- See SO: How do I merge two dictionaries in a single expression? for merging with the new augmented assignment version.
- This answer.
>>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}
>>> e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
>>> d | e
{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
>>> e | d
{'aardvark': 'Ethel', 'spam': 1, 'eggs': 2, 'cheese': 3}
- Additional examples from the PEP.
Motivation
The current ways to merge two dicts have several disadvantages:
dict.update
d1.update(d2) modifies d1 in-place. e = d1.copy(); e.update(d2) is not an expression and needs a temporary variable.
{**d1, **d2}
Dict unpacking looks ugly and is not easily discoverable. Few people would be able to guess what it means the first time they see it, or think of it as the "obvious way" to merge two dicts.