(dict | dict 2) - how python dictionary alternative operator works?

雨燕双飞 提交于 2020-07-10 05:14:36

问题


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 |

  1. Simpler and more uniform across dictionaries, sets, lists.
  2. Type-preserving. Particularly the old method 2 is not preserving the type of dictionaries.
  3. 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.)
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!