
1、字典合并返回新字典,该字典由左操作数和右操作数合并,各操作数必须为dict(或dict子类实例)。如果两个操作数中有一个键,最后出现的值(即从右侧操作数的值)将被覆盖。
1 2 3 4 5 6 | >>> 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_方法)或重复对象。
1 2 3 4 5 6 7 8 | >>> 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}
|
以上就是python字典合并的规范,希望对大家有所帮助。更多编程基础知识学习:python学习网
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。