为什么Python中dict不要轻易用update()操作赋值?

dict类型的update()介绍

“”" D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] “”"

如果参数E存在,并且有一个 .keys方法,那么执行for k in E: D[k] = E[k]如果参数E存在,但是没有 .keys方法,那么执行for k, v in E: D[k] = v

实例

以下实例展示了 update() 方法的使用方法:

>>> d = {‘one’:1,’two’:2}

>>> d.update({‘three’:3,’four’:4}) # 传一个字典

>>> print(d)

{‘one’: 1, ‘four’: 4, ‘three’: 3, ‘two’: 2}

>>> d.update(five=5,six=6) # 传关键字

>>> print(d)

{‘one’: 1, ‘four’: 4, ‘three’: 3, ‘five’: 5, ‘two’: 2, ‘six’: 6}

>>> d.update([(‘seven’,7),(‘eight’,8)]) # 传一个包含一个或多个元组的列表

>>> print(d)

{‘seven’: 7, ‘one’: 1, ‘four’: 4, ‘three’: 3, ‘five’: 5, ‘two’: 2, ‘six’: 6, ‘eight’: 8}

>>> d.update(([‘nice’,9],[‘ten’,10])) # 传一个包含一个或多个列表的元组

>>> print(d)

{‘seven’: 7, ‘one’: 1, ‘four’: 4, ‘three’: 3, ‘ten’: 10, ‘five’: 5, ‘nice’: 9, ‘two’: 2, ‘six’: 6, ‘eight’: 8}

>>> d.update(zip([‘eleven’,’twelve’],[11,12])) # 传一个zip()函数

>>> print(d)

{‘one’: 1, ‘four’: 4, ‘three’: 3, ‘twelve’: 12, ‘ten’: 10, ‘seven’: 7, ‘six’: 6, ‘eleven’: 11, ‘two’: 2, ‘nice’: 9, ‘five’: 5, ‘eight’: 8}

>>> d.update(one=111,two=222) # 使用以上任意方法修改存在的键对应的值

>>> print(d)

{‘one’: 111, ‘four’: 4, ‘three’: 3, ‘twelve’: 12, ‘ten’: 10, ‘seven’: 7, ‘six’: 6, ‘eleven’: 11, ‘two’: 222, ‘nice’: 9, ‘five’: 5, ‘eight’: 8}

为什么不要用

不是不用,而是分清使用场景性能方面 dict[‘key’] = 'value’这种方式性能更高update方法通过遍历dict2来更新dict1

update使用的场景

涉及两个字典合并的操作,使用dict1.update(dict2)

总结

虽然update和赋值都可以达到改变字典的目的。但是update的实现方式是遍历字典赋值,性能比直接赋值当然要低一些。因此给字典赋值,最好使用dict[‘key’] = ‘value’ 效果更好