python字典合并有哪些规范?

323次阅读
没有评论

python字典合并有哪些规范?

1、字典合并返回新字典,该字典由左操作数和右操作数合并,各操作数必须为dict(或dict子类实例)。如果两个操作数中有一个键,最后出现的值(即从右侧操作数的值)将被覆盖。

>>> 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}

2、扩展赋值的行为与字典的update方法完全相同,支持实现映射协议(更准确地实现keys和__getitem_方法)或重复对象。

>>> d | [('spam', 999)]   # “原理”章节中提到限制操作数的类型,不是字典或字典子类就报错
Traceback (most recent call last):
  ...
TypeError: can only merge dict (not "list") to dict
 
>>> d |= [('spam', 999)]  # “原理”章节中提到允许就地运算符接受更广泛的类型,其行为和 update 一样,接受键值对迭代对象
>>> d
{'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel', 'spam': 999}
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-04-26发表,共计964字。
新手QQ群:570568346,欢迎进群讨论 Python51学习