
上QQ阅读APP看书,第一时间看更新
5.3.5 update()方法
update()方法用于把一个字典A的键值对更新到另一个字典B里。update()方法的语法格式如下:
dict.update(dict2)
此语法中,dict代表指定字典,dict2代表添加到指定字典dict里的字典。该方法没有任何返回值。
该方法的使用示例如下:
>>> student={'小萌': '000', '小智': '001'} >>> student2={'小李':'003'} >>> print(f'原student字典为:{student}') 原student字典为:{'小萌': '000', '小智': '001'} >>> student.update(student2) >>> print(f'新student字典为:{student}') 新student字典为:{'小萌': '000', '小智': '001', '小李': '003'} >>> student3={'小李':'005'} >>> student.update(student3) #对相同项覆盖 >>> print(f'新student字典为:{student}') 新student字典为:{'小萌': '000', '小智': '001', '小李': '005'}
由输出结果可以看到,使用update()方法,可以将一个字典中的项添加到另一个字典中,如果有相同的键就会将键对应的值覆盖。
在实际项目应用中,update()方法的使用不是很多,一般用于将两个字典合并。