问题
What does dict | dict2
operation do in Python?
I came across it and I am not sure what it actually does and when to use it.
回答1:
New dictionary update and merge operators (Python >= 3.9)
Starting with Python 3.9 it is possible to use merge (|
) and update (|=
) operators in Python. They are described in PEP-584. Essentially the semantics is that the value for the last duplicate key overwrites previous values and becomes the values for the key in the resulting dictionary.
These operators are making it easier to make one dictionary out of two so they are equivalent to the following operations:
e = d1 | d2 # merge since Python 3.9
Is equivalent to older:
# Python < 3.9
# merge - solution 1
e = d1.copy(); e.update(d2)
# merge - solution 2
e = {**d1, **d2}
And:
d1 |= d2 # merge since Python 3.9
Is equivalent to older:
# Python < 3.9
# merge inplace - solution 1
d1.update(d2)
# merge inplace - solution 2
d1 = {**d1, **d2}
Advantages of |
- Simpler and more uniform across dictionaries, sets, lists.
- Type-preserving. Particularly the old method 2 is not preserving the type of dictionaries.
d1 | d2
is an expression and the old approaches are not which can come handy whenever the result is to be used immediately (e.g. passing parameters, list comprehensions, etc.)- Efficiency (in some cases there are not going to be created temporary dictionaries while in the previous versions of Python they were).
来源:https://stackoverflow.com/questions/62498441/dict-dict-2-how-python-dictionary-alternative-operator-works