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

本文详细介绍了Python中字典类型dict的update()方法的使用方法及应用场景,包括如何使用update()方法更新字典,以及在何种情况下使用该方法会更有效。同时,对比了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’ 效果更好

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值