Python字典中.copy()复制方法与a = b 直接赋值的区别,.pop()方法、.setdefault()方法、.update()方法的使用

Python字典中.copy()复制方法与a = b 直接赋值的区别

1.Python字典中.copy()复制方法的使用

>>> dict1 = {1:'one',2:'two',3:'three'}
>>> dict2 = dict1.copy()      #这里的dict1.copy()为前拷贝方法
>>> dict3 = dict1
>>> dict3
{1: 'one', 2: 'two', 3: 'three'}
>>> dict2
{1: 'one', 2: 'two', 3: 'three'}
>>> dict1
{1: 'one', 2: 'two', 3: 'three'}

前拷贝之后查看id()地址,推测是否指向同一个字典。如下:可以发现dict1与dict3是直接赋值,所以地址相同,指向同一个字典,只是标签不同。而dict2是拷贝的,有新的地址,指向的不是同一个字典。

>>> id(dict1)
1596603450616
>>> id(dict3)
1596603450616

>>> id(dict2)
1596603451816

2.Python中.pop()方法的使用
由于第一步中dict1和dict3指向的是同一个字典,所以当dict3改变时,dict1也会跟着改变,但dict2并没有改变。

>>> dict3[4] = 'four'
>>> dict3
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> dict1
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> dict2
{1: 'one', 2: 'two', 3: 'three'}

将dict1中的索引值为2的元素pop出去,会直接删除‘two’:

>>> dict1.pop(2)
'two'
>>> dict1
{1: 'one', 3: 'three', 4: 'four'}

使用.popitem()方法,会随机进行删除一条,因为字典中没有一定的顺序:

>>> dict1.popitem()
(4, 'four')

3.Python中.setdefault()方法的使用
在字典中添加内容

>>> dict1
{1: 'one', 3: 'three'}
>>> dict1.setdefault('大雄')
>>> dict1
{1: 'one', 3: 'three', '大雄': None}
>>> dict1.setdefault(5,'five')
'five'
>>> dict1
{1: 'one', 3: 'three', '大雄': None, 5: 'five'}

4.Python中.update()方法的使用
update()方法:是利用字典或映射关系去更新另外一个字典。
例如:在dict1中用update方法更新,根据dict2的内容。若dict1中有相同的键,则直接把对应的值填入该位置,将None替换为’哆啦A梦‘。

>>> dict1
{1: 'one', 3: 'three', '大雄': None, 5: 'five'}

>>> dict2 = {'大雄':'哆啦A梦'}
>>> dict1.update(dict2)

>>> dict1
{1: 'one', 3: 'three', '大雄': '哆啦A梦', 5: 'five'}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值