(dict | dict 2)-python字典替代运算符如何工作? [英] (dict | dict 2) - how python dictionary alternative operator works?

查看:118
本文介绍了(dict | dict 2)-python字典替代运算符如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dict | dict2操作在Python中做什么?

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.

推荐答案

新的字典更新和合并运算符(Python> = 3.9)

从Python 3.9开始,可以在Python中使用 merge (|)和 update (|=)运算符.它们在 PEP-584 中进行了描述.本质上,语义是最后一个重复键的值会覆盖以前的值,并成为结果字典中键的值.

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    

等效于旧版本:

# Python < 3.9

# merge - solution 1
e = d1.copy(); e.update(d2)

# merge - solution 2
e = {**d1, **d2}

并且:

d1 |= d2  # merge since Python 3.9    

等效于旧版本:

# Python < 3.9

# merge inplace - solution 1
d1.update(d2)

# merge inplace - solution 2
d1 = {**d1, **d2}

|

Advantages of |

  1. 在字典,集合,列表之间更简单,更统一.
  2. 保留类型.特别是旧方法2并没有保留字典的类型.
  3. d1 | d2是一个表达式,但无论何时要立即使用结果(例如,传递参数,列表推导等),旧方法都不会很方便
  4. 效率(在某些情况下,在以前的Python版本中不会创建临时字典).
  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).

这篇关于(dict | dict 2)-python字典替代运算符如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆