The other day, PEP 584 (Add Union Operators To dict) became Final Commit / python / peps / pull / 1440) I saw it. So, this time I will read PEP 584.
d1.update (d2)
rewrites d1, there are occasions when a temporary variable is prepared, and since it is not an expression, it cannot be used as a parameter.{** d1, ** d2}
is not goodcollections.ChainMap
is minor and has the problem of rewriting d1dict (d1, ** d2)
will result in an error if the key is not a string|
operator to be used to combine dictionariesCombine the two dictionaries with d1 | d2
. If you have the same key, it will be overwritten with the contents of the dictionary on the right, so it is not commutative (the order of the keys in the new dictionary will also change).
>>> 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}
It also supports the | =
operator.
>>> d |= e
>>> d
{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
d = dict (d1); d.update (d2)
has been written many times, so I'm happyRecommended Posts